<?php
namespace App\Event;
use Doctrine\ORM\Query;
use Doctrine\ORM\Tools\Pagination\CountWalker;
use Doctrine\ORM\Tools\Pagination\Paginator;
use Knp\Component\Pager\Event\ItemsEvent;
use Knp\Component\Pager\Event\Subscriber\Paginate\Doctrine\ORM\QuerySubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Request;
class PaginationEventSubscriber extends QuerySubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
'knp_pager.items' => ['items', 0]
];
}
public function items(ItemsEvent $event): void
{
if (!$event->target instanceof Query) {
return;
}
$event->stopPropagation();
$useOutputWalkers = false;
if (isset($event->options['wrap-queries'])) {
$useOutputWalkers = $event->options['wrap-queries'];
}
$offset = $event->getOffset();
$request = Request::createFromGlobals();
if (null !== $optionalOffset = $request->get('paginate_optional_offset')) {
$offset += $optionalOffset;
}
$event->target
->setFirstResult($offset)
->setMaxResults($event->getLimit())
->setHint(CountWalker::HINT_DISTINCT, $event->options['distinct'])
;
$fetchJoinCollection = true;
if ($event->target->hasHint(self::HINT_FETCH_JOIN_COLLECTION)) {
$fetchJoinCollection = $event->target->getHint(self::HINT_FETCH_JOIN_COLLECTION);
} else if (isset($event->options['distinct'])) {
$fetchJoinCollection = $event->options['distinct'];
}
$paginator = new Paginator($event->target, $fetchJoinCollection);
$paginator->setUseOutputWalkers($useOutputWalkers);
if (($count = $event->target->getHint(self::HINT_COUNT)) !== false) {
$event->count = (int) $count;
} else {
$event->count = count($paginator);
}
$event->items = iterator_to_array($paginator);
}
}