<?php declare(strict_types=1);
namespace BaumarktTheme\Subscriber;
use Shopware\Core\Content\Product\Aggregate\ProductMedia\ProductMediaEntity;
use Shopware\Core\Content\Product\Events\ProductCrossSellingIdsCriteriaEvent;
use Shopware\Core\Content\Product\Events\ProductListingCriteriaEvent;
use Shopware\Core\Content\Product\Events\ProductListingResultEvent;
use Shopware\Core\Content\Product\Events\ProductSearchCriteriaEvent;
use Shopware\Core\Content\Product\Events\ProductSearchResultEvent;
use Shopware\Core\Content\Product\SalesChannel\SalesChannelProductEntity;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ListingSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [
ProductListingCriteriaEvent::class => 'onProductListingCriteria',
ProductSearchCriteriaEvent::class => 'onProductSearchCriteria',
ProductListingResultEvent::class => 'handleResult',
ProductSearchResultEvent::class => 'handleResult',
ProductCrossSellingIdsCriteriaEvent::class => 'onCrossSellingProductListCriteria'
];
}
public function onProductSearchCriteria(ProductSearchCriteriaEvent $event)
{
$criteria = $event->getCriteria();
$criteria->addAssociation('media');
}
public function onProductListingCriteria(ProductListingCriteriaEvent $event)
{
$criteria = $event->getCriteria();
$criteria->addAssociation('media');
}
public function onCrossSellingProductListCriteria(ProductCrossSellingIdsCriteriaEvent $event)
{
$criteria = $event->getCriteria();
$criteria->addAssociation('media');
}
public function handleResult(ProductListingResultEvent $event): void
{
/** @var SalesChannelProductEntity $product */
foreach ($event->getResult()->getEntities() as $product) {
if (!$product->getMedia()) {
continue;
}
if ($product->getMedia()->count() < 2) {
continue;
}
$hoverPosition = 0;
if ($product->getCover() && $product->getCover()->getPosition() == 0) {
$hoverPosition = 1;
}
/** @var ProductMediaEntity $productMedia */
foreach ($product->getMedia() as $productMedia) {
if ($product->getCover() && $product->getCover()->getMediaId()) {
if ($productMedia->getPosition() == $hoverPosition) {
$product->addExtension("hover", $productMedia->getMedia());
break;
}
}
}
// Product media position is sometimes broken and its value is 1 for all product media
if (!$product->hasExtension("hover")) {
/** @var ProductMediaEntity $productMedia */
foreach ($product->getMedia() as $productMedia) {
if ($product->getCover() && $product->getCover()->getMediaId() && $productMedia->getMedia()) {
if ($product->getCover()->getMediaId() != $productMedia->getMediaId()) {
$product->addExtension("hover", $productMedia->getMedia());
break;
}
}
}
}
}
}
}