<?php declare(strict_types=1);
namespace Swag\EnterpriseSearch\PreviewSearch;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Swag\EnterpriseSearch\Search\SearchCriteriaEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
class PreviewSearchSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
SearchCriteriaEvent::class => 'handleRequest',
];
}
public function handleRequest(SearchCriteriaEvent $event): void
{
$request = $event->getRequest();
$criteria = $event->getCriteria();
if (!$request->get('explain', false)) {
return;
}
$this->handlePagination($request, $criteria);
}
private function handlePagination(Request $request, Criteria $criteria): void
{
$limit = $this->getLimit($request);
$page = $this->getPage($request);
$criteria->setOffset(($page - 1) * $limit);
$criteria->setLimit($limit);
$criteria->setTotalCountMode(Criteria::TOTAL_COUNT_MODE_EXACT);
}
private function getLimit(Request $request): int
{
$limit = $request->query->getInt('limit', 24);
if ($request->isMethod(Request::METHOD_POST)) {
$limit = $request->request->getInt('limit', $limit);
}
return $limit <= 0 ? 24 : $limit;
}
private function getPage(Request $request): int
{
$page = $request->query->getInt('page', 1);
if ($request->isMethod(Request::METHOD_POST)) {
$page = $request->request->getInt('page', $page);
}
return $page <= 0 ? 1 : $page;
}
}