<?php
namespace CoeProductNumberSearchSw6\Subscriber;
use Shopware\Core\Content\Product\SalesChannel\SalesChannelProductEntity;
use Shopware\Core\Defaults;
use Shopware\Core\Framework\DataAbstractionLayer\Search\EntitySearchResult;
use Shopware\Core\Framework\Feature;
use Shopware\Core\System\Snippet\Files\AbstractSnippetFile;
use Shopware\Storefront\Page\Suggest\SuggestPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Class SuggestPageSubscriber
* @package CoeProductNumberSearchSw6\Subscriber
* @author Jeffry Block <jeffry.block@codeenterprise.de>
*/
class SuggestPageSubscriber implements EventSubscriberInterface {
public static function getSubscribedEvents() {
return [
SuggestPageLoadedEvent::class => "onSuggestPageLoaded"
];
}
/**
* @param SuggestPageLoadedEvent $event
* @author Jeffry Block <jeffry.block@codeenterprise.de>
*/
public function onSuggestPageLoaded(SuggestPageLoadedEvent $event) :void{
/** @var string $term */
$term = $event->getPage()->getSearchTerm();
/** @var EntitySearchResult $result */
$result = $event->getPage()->getSearchResult();
#Check if the product number of the first result matches the search term
if($result->count() == 0){
return;
}
/** @var SalesChannelProductEntity $firstProduct */
$firstProduct = $result->first();
if($firstProduct === null){
return;
}
$res = $result->filter(function($product) use($term){
/** @var string lowercased term $t */
$t = strtolower(preg_replace("/\.(.*)/i", "", $term));
/** @var string productnumber of first found product $p */
$p = strtolower(preg_replace("/\.(.*)/i", "", $product->getProductNumber()));
return $p === $t;
});
if($res->count() > 0){
/*
* Since we can't use $res->setTotal(), we simply create a new
* result based on the original result but change the total.
*/
if ($res->getTotal() != 1 && !Feature::isActive('v6.5.0.0')) {
$res = new EntitySearchResult(
$res->getEntity(),
$res->getEntities()->count(), // overwrite the count
$res->getEntities(),
$res->getAggregations(),
$res->getCriteria(),
$res->getContext()
);
}
$event->getPage()->setSearchResult($res);
}
}
}