<?php
namespace App\EventListener;
use Doctrine\ORM\NativeQuery;
use Knp\Component\Pager\Event\ItemsEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
/**
* Class QueryPaginatorSubscriber.
*/
class QueryPaginatorSubscriber implements EventSubscriberInterface
{
/**
* @var SessionInterface
*/
private $session;
/**
* @var Request
*/
private $request;
/**
* @var RequestStack
*/
private $requestStack;
/**
* @param SessionInterface $session
* @param RequestStack $requestStack
*/
public function __construct(SessionInterface $session, RequestStack $requestStack)
{
$this->session = $session;
$this->requestStack = $requestStack;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return [
'knp_pager.items' => ['items', 1]
];
}
public function items(ItemsEvent $event)
{
if (!$event->target instanceof NativeQuery) {
return;
}
$request = $this->requestStack->getCurrentRequest();
$sortBy = $request->get('sort');
$sortDirection = $request->get('direction');
if (null !== $sortBy && '' !== $sortBy) {
$sql = $event->target->getSQL();
$sortedQuery = $sql . ' ORDER BY ' . $sortBy . ' ' . $sortDirection;
$event->target->setSQL($sortedQuery);
}
$event->count = count($event->target->getResult());
$event->items = array_slice($event->target->getResult(), $event->getOffset(), $event->getLimit());
$event->stopPropagation();
}
}