custom/static-plugins/CytexTheme/src/Subscriber/ListingSubscriber.php line 27

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace CytexTheme\Subscriber;
  3. use Shopware\Core\Content\Product\Events\ProductListingResultEvent;
  4. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  5. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  6. use Shopware\Core\Framework\Struct\ArrayStruct;
  7. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  8. class ListingSubscriber implements EventSubscriberInterface
  9. {
  10.     private EntityRepositoryInterface $productRepository;
  11.     public function __construct(EntityRepositoryInterface $productRepository)
  12.     {
  13.         $this->productRepository $productRepository;
  14.     }
  15.     public static function getSubscribedEvents(): array
  16.     {
  17.         return [
  18.             ProductListingResultEvent::class => 'onListResult'
  19.         ];
  20.     }
  21.     public function onListResult(ProductListingResultEvent $event)
  22.     {
  23.         $products $event->getResult()->getEntities();
  24.         $ids $products->getIds();
  25.         $criteria = new Criteria($ids);
  26.         $criteria->addAssociation('media');
  27.         $results $this->productRepository->search($criteria$event->getContext());
  28.         foreach ($results as $product) {
  29.             $media $product->getMedia()->getElements();
  30.             unset($media[$product->getCoverId()]);
  31.             if (empty($media)) {
  32.                 continue;
  33.             }
  34.             $mainProduct $products->get($product->getId());
  35.             if (!$mainProduct) {
  36.                 continue;
  37.             }
  38.             $mainProduct->addExtension('alternativeCover', new ArrayStruct(['cover' => reset($media)->getMedia()]));
  39.         }
  40.     }
  41. }