Last active
December 11, 2015 07:08
-
-
Save ChubV/4563653 to your computer and use it in GitHub Desktop.
Add DBAL QueryBuilder support for KnpPaginatorBundle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace ChubV\ToolkitBundle\Subscriber; | |
use Symfony\Component\EventDispatcher\EventSubscriberInterface; | |
use Knp\Component\Pager\Event\ItemsEvent; | |
use Doctrine\DBAL\Query\QueryBuilder; | |
class PaginationSubscriber implements EventSubscriberInterface | |
{ | |
public function items(ItemsEvent $event) | |
{ | |
if ($event->target instanceof QueryBuilder) { | |
/** @var QueryBuilder $target */ | |
$target = $event->target; | |
//get the query | |
$sql = $target->getSQL(); | |
//count results | |
$qb = clone $target; | |
$qb->resetQueryParts() | |
->select('count(*) as cnt') | |
->from('(' . $sql . ')', 'ololoshke_trololoshke'); | |
$event->count = $qb->execute() | |
->fetchColumn(0); | |
//if there is results | |
$event->items = []; | |
if ($event->count) { | |
$q = clone $target; | |
$q->setFirstResult($event->getOffset()) | |
->setMaxResults($event->getLimit()); | |
$event->items = $q->execute() | |
->fetchAll(); | |
} | |
$event->stopPropagation(); | |
} | |
} | |
public static function getSubscribedEvents() | |
{ | |
return array( | |
'knp_pager.items' => array('items', 10 /*make sure to transform before any further modifications*/) | |
); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
services: | |
toolkit.dbal.paginator: | |
class: ChubV\ToolkitBundle\Subscriber\PaginationSubscriber | |
tags: | |
- { name: knp_paginator.subscriber } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment