<?php declare(strict_types=1);
namespace Proclane\WegmannTheme\Subscriber;
use Shopware\Core\Content\Product\Events\ProductListingCriteriaEvent;
use Shopware\Core\Content\Product\Events\ProductSearchCriteriaEvent;
use Shopware\Core\Content\Product\Events\ProductSearchResultEvent;
use Shopware\Core\Content\Product\Events\ProductSuggestCriteriaEvent;
use Shopware\Core\Content\Product\SalesChannel\Exception\ProductSortingNotFoundException;
use Shopware\Core\Content\Product\SalesChannel\Listing\FilterCollection;
use Shopware\Core\Content\Product\SalesChannel\Sorting\ProductSortingCollection;
use Shopware\Core\Content\Product\SalesChannel\Sorting\ProductSortingEntity;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Aggregation\Metric\EntityAggregation;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
class ProductListingFeaturesSubscriber implements EventSubscriberInterface
{
private SystemConfigService $systemConfigService;
private $salesChannelProductRepository;
public function __construct(
SystemConfigService $systemConfigService,
$salesChannelProductRepository)
{
$this->systemConfigService = $systemConfigService;
$this->salesChannelProductRepository = $salesChannelProductRepository;
}
public static function getSubscribedEvents()
{
return [
ProductSuggestCriteriaEvent::class => [
['handleSearchSuggestEvent', 200]
],
ProductSearchCriteriaEvent::class => [
['handleSearchSuggestEvent', 200]
]
];
}
public function handleSearchSuggestEvent(ProductSuggestCriteriaEvent|ProductSearchCriteriaEvent $event): void
{
$criteria = $event->getCriteria();
$request = $event->getRequest();
$salesChannelContext = $event->getSalesChannelContext();
$cloneCriteria = clone $criteria;
$term = $request->get('search');
$cloneCriteria->setTerm(null);
$cloneCriteria->addFilter(new EqualsFilter('productNumber', $term));
//in base al term fare regex
$pattern = '/^(?=.*\d)(?=.*-).+$/';
$exactMatch = false;
if (preg_match($pattern, $term)) {
$ids = $this->salesChannelProductRepository->searchIds($cloneCriteria, $salesChannelContext);
//se count < 0 allora assegno al criteria
if($ids->getTotal() > 0) {
$criteria->setTerm(null);
$criteria->addFilter(new EqualsFilter('productNumber', $term));
$exactMatch = true;
}
}
$criteria->assign(['exactMatch' => $exactMatch]);
}
}