<?php declare(strict_types=1);
namespace CytexTheme\Subscriber;
use Shopware\Core\Content\Product\Events\ProductListingResultEvent;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\Struct\ArrayStruct;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ListingSubscriber implements EventSubscriberInterface
{
private EntityRepositoryInterface $productRepository;
public function __construct(EntityRepositoryInterface $productRepository)
{
$this->productRepository = $productRepository;
}
public static function getSubscribedEvents(): array
{
return [
ProductListingResultEvent::class => 'onListResult'
];
}
public function onListResult(ProductListingResultEvent $event)
{
$products = $event->getResult()->getEntities();
$ids = $products->getIds();
$criteria = new Criteria($ids);
$criteria->addAssociation('media');
$results = $this->productRepository->search($criteria, $event->getContext());
foreach ($results as $product) {
$media = $product->getMedia()->getElements();
unset($media[$product->getCoverId()]);
if (empty($media)) {
continue;
}
$mainProduct = $products->get($product->getId());
if (!$mainProduct) {
continue;
}
$mainProduct->addExtension('alternativeCover', new ArrayStruct(['cover' => reset($media)->getMedia()]));
}
}
}