custom/plugins/AtlProductConfigurator/src/Subscriber/ProductLoadedSubscriber.php line 39

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Atl\ProductConfigurator\Subscriber;
  3. use Atl\ProductConfigurator\Extension\Content\Product\ProductExtensionEntity;
  4. use Atl\ProductConfigurator\Migration\Migration1628124328ProductExtension;
  5. use Shopware\Core\Content\Product\ProductEvents;
  6. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  7. use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
  8. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  9. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  10. use Shopware\Core\Framework\DataAbstractionLayer\Search\Sorting\FieldSorting;
  11. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  12. class ProductLoadedSubscriber implements EventSubscriberInterface
  13. {
  14.     /**
  15.      * @var EntityRepositoryInterface
  16.      */
  17.     private $productExtensionRepository;
  18.     public function __construct(EntityRepositoryInterface $productExtensionRepository)
  19.     {
  20.         $this->productExtensionRepository $productExtensionRepository;
  21.     }
  22.     public static function getSubscribedEvents(): array
  23.     {
  24.         return [
  25.             ProductEvents::PRODUCT_LOADED_EVENT => 'onProductsLoaded'
  26.         ];
  27.     }
  28.     /**
  29.      * @param EntityLoadedEvent $event
  30.      */
  31.     public function onProductsLoaded(EntityLoadedEvent $event): void
  32.     {
  33.         $products $event->getEntities();
  34.         if (count($products) > 1) {
  35.             return;
  36.         }
  37.         $product $products[0];
  38.         $productId $product->getId();
  39.         $criteria = new Criteria();
  40.         $criteria->addFilter(new EqualsFilter('productId'$productId));
  41.         $criteria->setLimit(1);
  42.         $criteria->addAssociation('atlProductConfigurator.media');
  43.         $criteria->getAssociation("atlProductConfigurator.atlProductConfiguratorFields")->addSorting(new FieldSorting("position"FieldSorting::ASCENDING));
  44.         $criteria->addAssociation("atlProductConfigurator.atlProductConfiguratorFields.media");
  45.         /** @var ProductExtensionEntity $productExtension */
  46.         $productExtension $this->productExtensionRepository->search($criteria$event->getContext())->first();
  47.         if (empty($productExtension)) {
  48.             return;
  49.         }
  50.         $ext $product->getExtensions();
  51.         $ext[Migration1628124328ProductExtension::PRODUCT_EXTENSION] = $productExtension->getAtlProductConfigurator();
  52.         $product->setExtensions($ext);
  53.     }
  54. }