custom/plugins/WbfkProductLinks/src/Subscriber/ProductSubscriber.php line 40

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Wbfk\ProductLinks\Subscriber;
  4. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
  5. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  6. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  7. use Shopware\Core\Framework\Struct\StructCollection;
  8. use Shopware\Storefront\Page\Product\ProductPageCriteriaEvent;
  9. use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. class ProductSubscriber implements EventSubscriberInterface
  12. {
  13.     /**
  14.      * @var EntityRepository
  15.      */
  16.     private EntityRepository $productLinkRepository;
  17.     public function __construct(EntityRepository $productLinkRepository)
  18.     {
  19.         $this->productLinkRepository $productLinkRepository;
  20.     }
  21.     public static function getSubscribedEvents(): array
  22.     {
  23.         return [
  24.             ProductPageCriteriaEvent::class => 'onProductCriteriaLoaded',
  25.             ProductPageLoadedEvent::class => 'loadProductPage',
  26.         ];
  27.     }
  28.     public function onProductCriteriaLoaded(ProductPageCriteriaEvent $event): void
  29.     {
  30.         $event->getCriteria()->addAssociation('wbfk_product_link');
  31.     }
  32.     public function loadProductPage(ProductPageLoadedEvent $event): void
  33.     {
  34.         // ToDo: This is a Fallback
  35.         // We can not set the product extension to "inherited".
  36.         // This would throw an error in the administration on saving a child product
  37.         // See: ProductExtension Definition
  38.         $product $event->getPage()->getProduct();
  39.         $productLinks $product->getExtension('wbfk_product_link');
  40.         $parentId $product->getParentId();
  41.         if ($parentId && (!$productLinks || count($productLinks->getElements()) == 0)) {
  42.             $criteria = new Criteria();
  43.             $criteria->addFilter(new EqualsFilter('productId'$parentId));
  44.             $parentProductLinks $this->productLinkRepository->search($criteria$event->getContext())->getEntities();
  45.             if ($parentProductLinks->count() > 0) {
  46.                 $product->addExtension('wbfk_product_link', new StructCollection($parentProductLinks->getElements()));
  47.             }
  48.         }
  49.     }
  50. }