<?php declare(strict_types=1);
namespace Swag\EnterpriseSearch\Product;
use Shopware\Core\Content\Product\Events\ProductSearchCriteriaEvent;
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 ProductSearchCriteriaSubscriber implements EventSubscriberInterface
{
/**
* @var EntityRepositoryInterface
*/
private $configRepository;
public function __construct(
EntityRepositoryInterface $configRepository
) {
$this->configRepository = $configRepository;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents(): array
{
return [
ProductSearchCriteriaEvent::class => 'onProductSearchCriteria',
];
}
public function onProductSearchCriteria(ProductSearchCriteriaEvent $event): void
{
$criteria = $event->getCriteria();
$salesChannelContext = $event->getSalesChannelContext();
$maxSearchCount = $this->fetchLimit($salesChannelContext);
if (!$maxSearchCount) {
return;
}
$criteria->setLimit($maxSearchCount);
}
/**
* @throws \Shopware\Core\Framework\DataAbstractionLayer\Exception\InconsistentCriteriaIdsException
*/
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->getMaxSearchCount();
}
}