src/Event/PaginationEventSubscriber.php line 23

Open in your IDE?
  1. <?php
  2. namespace App\Event;
  3. use Doctrine\ORM\Query;
  4. use Doctrine\ORM\Tools\Pagination\CountWalker;
  5. use Doctrine\ORM\Tools\Pagination\Paginator;
  6. use Knp\Component\Pager\Event\ItemsEvent;
  7. use Knp\Component\Pager\Event\Subscriber\Paginate\Doctrine\ORM\QuerySubscriber;
  8. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  9. use Symfony\Component\HttpFoundation\Request;
  10. class PaginationEventSubscriber extends QuerySubscriber implements EventSubscriberInterface
  11. {
  12. public static function getSubscribedEvents(): array
  13. {
  14. return [
  15. 'knp_pager.items' => ['items', 0]
  16. ];
  17. }
  18. public function items(ItemsEvent $event): void
  19. {
  20. if (!$event->target instanceof Query) {
  21. return;
  22. }
  23. $event->stopPropagation();
  24. $useOutputWalkers = false;
  25. if (isset($event->options['wrap-queries'])) {
  26. $useOutputWalkers = $event->options['wrap-queries'];
  27. }
  28. $offset = $event->getOffset();
  29. $request = Request::createFromGlobals();
  30. if (null !== $optionalOffset = $request->get('paginate_optional_offset')) {
  31. $offset += $optionalOffset;
  32. }
  33. $event->target
  34. ->setFirstResult($offset)
  35. ->setMaxResults($event->getLimit())
  36. ->setHint(CountWalker::HINT_DISTINCT, $event->options['distinct'])
  37. ;
  38. $fetchJoinCollection = true;
  39. if ($event->target->hasHint(self::HINT_FETCH_JOIN_COLLECTION)) {
  40. $fetchJoinCollection = $event->target->getHint(self::HINT_FETCH_JOIN_COLLECTION);
  41. } else if (isset($event->options['distinct'])) {
  42. $fetchJoinCollection = $event->options['distinct'];
  43. }
  44. $paginator = new Paginator($event->target, $fetchJoinCollection);
  45. $paginator->setUseOutputWalkers($useOutputWalkers);
  46. if (($count = $event->target->getHint(self::HINT_COUNT)) !== false) {
  47. $event->count = (int) $count;
  48. } else {
  49. $event->count = count($paginator);
  50. }
  51. $event->items = iterator_to_array($paginator);
  52. }
  53. }