<?php
declare(strict_types=1);
namespace Madco\Mykey\Subscriber;
use Madco\Mykey\Service\MykeyProductService;
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\Storefront\Page\Product\ProductPageCriteriaEvent;
use Shopware\Storefront\Page\Product\ProductPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductSubscriber implements EventSubscriberInterface
{
private MykeyProductService $mykeyProductService;
public function __construct(MykeyProductService $mykeyProductService)
{
$this->mykeyProductService = $mykeyProductService;
}
public static function getSubscribedEvents(): array
{
return [
ProductListingCriteriaEvent::class => 'onProductListingCriteria',
ProductPageCriteriaEvent::class => 'onProductPageCriteria',
ProductPageLoadedEvent::class => 'onProductPageLoaded',
ProductListingResultEvent::class => 'onProductListingResult',
#'sales_channel.product.loaded' => 'salesChannelProductLoaded',
ProductSearchCriteriaEvent::class => 'onProductListingCriteria',
ProductSearchResultEvent::class => 'onProductListingResult',
];
}
public function onProductPageCriteria(ProductPageCriteriaEvent $event): void
{
$event->getCriteria()->addAssociation('tags');
}
public function onProductListingCriteria(ProductListingCriteriaEvent $event): void
{
$event->getCriteria()->addAssociation('tags');
}
public function onProductPageLoaded(ProductPageLoadedEvent $event): void
{
$product = $event->getPage()->getProduct();
if ($this->mykeyProductService->isMykeyProduct($product)) {
$this->mykeyProductService->addMykeyExtensionToProduct($product);
}
}
public function onProductListingResult(ProductListingResultEvent $event): void
{
foreach ($event->getResult() as $product) {
if ($this->mykeyProductService->isMykeyProduct($product)) {
$this->mykeyProductService->addMykeyExtensionToProduct($product);
}
}
}
}