adding the paginator to timeline

This commit is contained in:
Julien Fastré 2016-09-02 08:21:42 +02:00
parent 1b674f9141
commit 32f887d71f

View File

@ -20,6 +20,7 @@
namespace Chill\MainBundle\Timeline;
use Doctrine\ORM\Query\ResultSetMapping;
use Doctrine\DBAL\Types\Type;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
@ -59,19 +60,46 @@ class TimelineBuilder implements ContainerAwareInterface
*
* @param string $context
* @param array $args arguments defined by the bundle which create the context
* @param int $page first page = 0
* @param int $firstItem first item number
* @param int $number number of items by page
* @return string an HTML representation, must be included using `|raw` filter
*/
public function getTimelineHTML($context, array $args, $page = 0, $number = 20)
public function getTimelineHTML($context, array $args, $firstItem = 0, $number = 20)
{
$query = $this->buildUnionQuery($context, $args, $page, $number);
$fetched = $this->runQuery($query);
$union = $this->buildUnionQuery($context, $args);
//add ORDER BY clause and LIMIT
$query = $union . sprintf(' ORDER BY date DESC LIMIT %d OFFSET %d',
$number, $firstItem);
// run query and handle results
$fetched = $this->runUnionQuery($query);
$entitiesByKey = $this->getEntities($fetched, $context);
return $this->render($fetched, $entitiesByKey, $context, $args);
}
/**
* Return the number of items for the given context and args
*
* @param unknown $context
* @param array $args
* @return mixed|\Doctrine\DBAL\Driver\Statement|NULL
*/
public function countItems($context, array $args)
{
$union = $this->buildUnionQuery($context, $args);
// embed the union query inside a count query
$count = sprintf('SELECT COUNT(sq.id) AS total FROM (%s) as sq', $union);
$rsm = (new ResultSetMapping())
->addScalarResult('total', 'total', Type::INTEGER);
return $this->em->createNativeQuery($count, $rsm)
->getSingleScalarResult();
}
/**
* add a provider id
*
@ -114,7 +142,7 @@ class TimelineBuilder implements ContainerAwareInterface
* @return string
* @throws \LogicException if no builder have been defined for this context
*/
private function buildUnionQuery($context, array $args, $page, $number)
private function buildUnionQuery($context, array $args)
{
//throw an exception if no provider have been defined for this context
if (!array_key_exists($context, $this->providers)) {
@ -129,9 +157,6 @@ class TimelineBuilder implements ContainerAwareInterface
$append = ($union === '') ? $select : ' UNION '.$select;
$union .= $append;
}
//add ORDER BY clause and LIMIT
$union .= sprintf(' ORDER BY date DESC LIMIT %d OFFSET %d',
$number, $page * $number);
return $union;
}
@ -168,7 +193,7 @@ class TimelineBuilder implements ContainerAwareInterface
* @param string $query
* @return array
*/
private function runQuery($query)
private function runUnionQuery($query)
{
$resultSetMapping = (new ResultSetMapping())
->addScalarResult('id', 'id')