<?php declare(strict_types=1);
namespace SanettaTheme\Subscriber;
use Monolog\Logger;
use SanettaTheme\Service\VariantLoader;
use SanettaTheme\Storefront\Event\ProductHoverLoadedEvent;
use Shopware\Core\Content\Product\Events\ProductListingResultEvent;
use Shopware\Core\Content\Product\Events\ProductSearchResultEvent;
use Shopware\Core\Content\Product\ProductCollection;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Throwable;
class ProductHover implements EventSubscriberInterface
{
protected VariantLoader $variantLoader;
protected Logger $logger;
public static function getSubscribedEvents(): array
{
return [
ProductListingResultEvent::class => [
['handleProductListingLoadedRequest', 201],
],
ProductSearchResultEvent::class => [
['handleProductListingLoadedRequest', 201],
],
ProductHoverLoadedEvent::class => [
['handleProductBoxLoadedRequest', 201],
],
];
}
public function __construct(VariantLoader $loader, Logger $logger)
{
$this->variantLoader = $loader;
$this->logger = $logger;
}
public function handleProductListingLoadedRequest(ProductListingResultEvent $event): void
{
$products = $event->getResult()->getEntities();
try {
$this->variantLoader->load($products, $event->getSalesChannelContext());
} catch (Throwable $e) {
$this->logger->error(
'Could not load variants.',
[
'productIds' => $products->getIds(),
'throwable' => [
'class' => get_class($e),
'message' => $e->getMessage(),
'code' => $e->getCode(),
],
]
);
}
}
public function handleProductBoxLoadedRequest(ProductHoverLoadedEvent $event): void
{
$product = $event->getProduct();
try {
$this->variantLoader->load(
new ProductCollection([$product]),
$event->getSalesChannelContext()
);
} catch (Throwable $e) {
$this->logger->error(
'Could not load variants.',
[
'productIds' => $product->getId(),
'throwable' => [
'class' => get_class($e),
'message' => $e->getMessage(),
'code' => $e->getCode(),
],
]
);
}
}
}