vendor/crehler/mojebambino-variants-advanced/src/Subscriber/ProductSubscriber.php line 31

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Crehler\VariantsAdvanced\Subscriber;
  3. use Crehler\VariantsAdvanced\Struct\ParentProduct;
  4. use Shopware\Core\Content\Product\SalesChannel\SalesChannelProductEntity;
  5. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  6. use Shopware\Core\System\SalesChannel\Entity\SalesChannelRepositoryInterface;
  7. use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. class ProductSubscriber implements EventSubscriberInterface
  10. {
  11.     private SalesChannelRepositoryInterface $productRepository;
  12.     public function __construct(SalesChannelRepositoryInterface $productRepository)
  13.     {
  14.         $this->productRepository $productRepository;
  15.     }
  16.     /**
  17.      * @return array
  18.      */
  19.     public static function getSubscribedEvents(): array
  20.     {
  21.         return [
  22.             ProductPageLoadedEvent::class => 'onProductPageLoaded'
  23.         ];
  24.     }
  25.     public function onProductPageLoaded(ProductPageLoadedEvent $event): void
  26.     {
  27.         $product $event->getPage()->getProduct();
  28.         $parentName null;
  29.         if ($product->getParentId() !== null) {
  30.             /** @var SalesChannelProductEntity $parent */
  31.             $parent $this->productRepository->search(new Criteria([$product->getParentId()]), $event->getSalesChannelContext())->first();
  32.             if ($parent !== null) {
  33.                 $parentName $parent->getTranslation('name');
  34.             }
  35.         }
  36.         $product->addExtension('parentProduct', (new ParentProduct())->setName($parentName));
  37.     }
  38. }