<?php declare(strict_types=1);
namespace Swag\EnterpriseSearch\Product;
use Shopware\Core\Content\Product\Events\ProductSearchResultEvent;
use Shopware\Core\Content\Product\ProductEntity;
use Shopware\Core\Content\Product\ProductEvents;
use Shopware\Core\Framework\Struct\ArrayEntity;
use Shopware\Core\System\SalesChannel\Entity\SalesChannelRepositoryInterface;
use Swag\EnterpriseSearch\Common\SesExtension;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductSearchResultSubscriber implements EventSubscriberInterface
{
/**
* @var SalesChannelRepositoryInterface
*/
private $repository;
public function __construct(SalesChannelRepositoryInterface $repository)
{
$this->repository = $repository;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array
{
return [
ProductEvents::PRODUCT_SEARCH_RESULT => 'onProductSearchResult',
];
}
public function onProductSearchResult(ProductSearchResultEvent $event): void
{
if (!SesExtension::isExplanation($event->getContext())) {
return;
}
$ids = $this->repository->searchIds($event->getResult()->getCriteria(), $event->getSalesChannelContext());
$products = $event->getResult();
/** @var string $id */
foreach ($ids->getIds() as $id) {
if (!$products->has($id)) {
continue;
}
/** @var ProductEntity $product */
$product = $products->get($id);
// get access to the data of the search result
$product->addExtension('search', new ArrayEntity($ids->getDataOfId($id)));
}
}
}