<?php declare(strict_types=1);
namespace Swag\EnterpriseSearch\Product;
use Shopware\Core\Content\Product\Events\ProductSuggestCriteriaEvent;
use Shopware\Core\Content\Product\ProductDefinition;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\System\SalesChannel\SalesChannelContext;
use Swag\EnterpriseSearch\Configuration\GatewayConfigurationEntity;
use Swag\EnterpriseSearch\Configuration\GatewayNotConfiguredException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class ProductSuggestCriteriaSubscriber implements EventSubscriberInterface
{
/**
* @var EntityRepositoryInterface
*/
private $configRepository;
public function __construct(
EntityRepositoryInterface $configRepository
) {
$this->configRepository = $configRepository;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array
{
return [
ProductSuggestCriteriaEvent::class => 'onProductSuggestCriteria',
];
}
public function onProductSuggestCriteria(ProductSuggestCriteriaEvent $event): void
{
$criteria = $event->getCriteria();
$salesChannelContext = $event->getSalesChannelContext();
$machSuggestCount = $this->fetchLimit($salesChannelContext);
$criteria->setLimit($machSuggestCount);
}
private function fetchLimit(SalesChannelContext $salesChannelContext): int
{
$criteria = new Criteria();
$criteria
->setLimit(1)
->addFilter(new EqualsFilter('salesChannelId', $salesChannelContext->getSalesChannel()->getId()))
->addFilter(new EqualsFilter('entityName', ProductDefinition::ENTITY_NAME));
/** @var GatewayConfigurationEntity|null $configuration */
$configuration = $this->configRepository->search($criteria, $salesChannelContext->getContext())->first();
if ($configuration === null) {
throw new GatewayNotConfiguredException('Search not configured for ' . ProductDefinition::ENTITY_NAME);
}
return $configuration->getMaxSuggestCount();
}
}