vendor/knplabs/knp-components/src/Knp/Component/Pager/Event/Subscriber/Paginate/Doctrine/DBALQueryBuilderSubscriber.php line 16

Open in your IDE?
  1. <?php
  2. namespace Knp\Component\Pager\Event\Subscriber\Paginate\Doctrine;
  3. use Doctrine\DBAL\Query\QueryBuilder;
  4. use Knp\Component\Pager\Event\ItemsEvent;
  5. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  6. /**
  7.  * DBALQueryBuilderSubscriber.php
  8.  *
  9.  * @author Vladimir Chub <v@chub.com.ua>
  10.  */
  11. class DBALQueryBuilderSubscriber implements EventSubscriberInterface
  12. {
  13.     public function items(ItemsEvent $event): void
  14.     {
  15.         if ($event->target instanceof QueryBuilder) {
  16.             $target $event->target;
  17.         
  18.             // count results
  19.             $qb = clone $target;
  20.             
  21.             //reset count orderBy since it can break query and slow it down
  22.             $qb
  23.                 ->resetQueryPart('orderBy')
  24.             ;
  25.             
  26.             // get the query
  27.             $sql $qb->getSQL();
  28.             
  29.             $qb
  30.                 ->resetQueryParts()
  31.                 ->select('count(*) as cnt')
  32.                 ->from('(' $sql ')''dbal_count_tbl')
  33.             ;
  34.             $compat $qb->execute();
  35.             $event->count method_exists($compat'fetchColumn') ? $compat->fetchColumn(0) : $compat->fetchOne();
  36.             // if there is results
  37.             $event->items = [];
  38.             if ($event->count) {
  39.                 $qb = clone $target;
  40.                 $qb
  41.                     ->setFirstResult($event->getOffset())
  42.                     ->setMaxResults($event->getLimit())
  43.                 ;
  44.                 
  45.                 $event->items $qb
  46.                     ->execute()
  47.                     ->fetchAll()
  48.                 ;
  49.             }
  50.             
  51.             $event->stopPropagation();
  52.         }
  53.     }
  54.     public static function getSubscribedEvents(): array
  55.     {
  56.         return [
  57.             'knp_pager.items' => ['items'10 /*make sure to transform before any further modifications*/],
  58.         ];
  59.     }
  60. }