src/EventListener/QueryPaginatorSubscriber.php line 50

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Doctrine\ORM\NativeQuery;
  4. use Knp\Component\Pager\Event\ItemsEvent;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. use Symfony\Component\HttpFoundation\Request;
  7. use Symfony\Component\HttpFoundation\RequestStack;
  8. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  9. /**
  10.  * Class QueryPaginatorSubscriber.
  11.  */
  12. class QueryPaginatorSubscriber implements EventSubscriberInterface
  13. {
  14.     /**
  15.      * @var SessionInterface
  16.      */
  17.     private $session;
  18.     /**
  19.      * @var Request
  20.      */
  21.     private $request;
  22.     /**
  23.      * @var RequestStack
  24.      */
  25.     private $requestStack;
  26.     /**
  27.      * @param SessionInterface $session
  28.      * @param RequestStack     $requestStack
  29.      */
  30.     public function __construct(SessionInterface $sessionRequestStack $requestStack)
  31.     {
  32.         $this->session $session;
  33.         $this->requestStack $requestStack;
  34.     }
  35.     /**
  36.      * {@inheritdoc}
  37.      */
  38.     public static function getSubscribedEvents()
  39.     {
  40.         return [
  41.             'knp_pager.items' => ['items'1]
  42.         ];
  43.     }
  44.     public function items(ItemsEvent $event)
  45.     {
  46.         if (!$event->target instanceof NativeQuery) {
  47.             return;
  48.         }
  49.         $request $this->requestStack->getCurrentRequest();
  50.         $sortBy $request->get('sort');
  51.         $sortDirection $request->get('direction');
  52.         if (null !== $sortBy && '' !== $sortBy) {
  53.             $sql $event->target->getSQL();
  54.             $sortedQuery $sql ' ORDER BY ' $sortBy ' ' $sortDirection;
  55.             $event->target->setSQL($sortedQuery);
  56.         }
  57.         $event->count count($event->target->getResult());
  58.         $event->items array_slice($event->target->getResult(), $event->getOffset(), $event->getLimit());
  59.         $event->stopPropagation();
  60.     }
  61. }