custom/plugins/SchilderSysteme/src/Subscriber/ProductSubscriber.php line 42

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace SchilderSysteme\Subscriber;
  4. use SchilderSysteme\Traits\ThemeTrait;
  5. use Shopware\Core\Framework\Context;
  6. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  7. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  8. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  9. use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. class ProductSubscriber implements EventSubscriberInterface
  12. {
  13.     use ThemeTrait;
  14.     private $productRepository;
  15.     private $themeRepository;
  16.     public function __construct(
  17.         EntityRepositoryInterface $productRepository,
  18.         EntityRepositoryInterface $themeRepository
  19.     )
  20.     {
  21.         $this->productRepository $productRepository;
  22.         $this->themeRepository $themeRepository;
  23.     }
  24.     public static function getSubscribedEvents(): array
  25.     {
  26.         return [
  27.             ProductPageLoadedEvent::class => 'loadVariants'
  28.         ];
  29.     }
  30.     /**
  31.      * Add all variants info for displayed products
  32.      *
  33.      * @param ProductPageLoadedEvent $event
  34.      */
  35.     public function loadVariants(ProductPageLoadedEvent $event)
  36.     {
  37.         if(!$this->isCorrectTheme($event->getContext(), $event->getSalesChannelContext(), $this->themeRepository)){
  38.             return;
  39.         }
  40.         $product $event->getPage()->getProduct();
  41.         $context $event->getContext();
  42.         if(!$product->getParentId()){
  43.             return;
  44.         }
  45.         $variants $this->getVariants($product->getParentId(), $context);
  46.         $customFields $product->getCustomFields();
  47.         $customFields['variants'] = $variants;
  48.         $product->setCustomFields($customFields);
  49.     }
  50.     /**
  51.      * Get variants with properties
  52.      *
  53.      * @param $parentId
  54.      * @param Context $context
  55.      * @return array
  56.      */
  57.     private function getVariants($parentIdContext $context)
  58.     {
  59.         $parentFilter = new EqualsFilter('parentId'$parentId);
  60.         $criteria = (new Criteria())
  61.             ->addFilter($parentFilter)
  62.             ->addAssociation('options.group')
  63.             ->addAssociation('prices');
  64.         return $this->productRepository->search($criteria$context)->getElements();
  65.     }
  66. }