Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Pagination with New Storage Engine
<?php
namespace Bolt\Extension\Bolt\JsonApi\Storage\Query\Handler;
use Bolt\Extension\Bolt\JsonApi\Storage\Query\PagingResultSet;
use Bolt\Storage\Query\ContentQueryParser;
class PagingHandler
{
public function __invoke(ContentQueryParser $contentQuery)
{
$set = new PagingResultSet();
foreach ($contentQuery->getContentTypes() as $contenttype) {
$query = $contentQuery->getService('select');
$repo = $contentQuery->getEntityManager()->getRepository($contenttype);
$query->setQueryBuilder($repo->createQueryBuilder($contenttype));
$query->setContentType($contenttype);
$query->setParameters($contentQuery->getParameters());
$query2 = clone $query->getQueryBuilder();
//Get count
$totalItems = $query2->select("COUNT(*) as total")->execute()->fetch();
$contentQuery->runDirectives($query);
$result = $repo->queryWith($query);
if ($result) {
$set->add($result, $contenttype);
$set->setTotalResults($totalItems);
}
}
}
}
<?php
namespace Bolt\Extension\Bolt\JsonApi\Storage\Query\Handler\Directive;
use Bolt\Extension\Bolt\JsonApi\Converter\Parameter\Type\Page;
use Bolt\Storage\Query\QueryInterface;
class PagerHandler
{
/**
* @param QueryInterface $query
* @param Page $page
*/
public function __invoke(QueryInterface $query, Page $page)
{
//Get offset
$offset = ($page->getNumber()-1) * $page->getSize();
$query->getQueryBuilder()->setFirstResult($offset);
$query->getQueryBuilder()->setMaxResults($page->getSize());
}
}
<?php
namespace Bolt\Extension\Bolt\JsonApi\Storage\Query;
use Bolt\Storage\Query\QueryResultset;
class PagingResultSet extends QueryResultset
{
protected $totalResults;
/**
* @return mixed
*/
public function getTotalResults()
{
return $this->totalResults;
}
/**
* @param mixed $totalResults
* @return PagingResultSet
*/
public function setTotalResults($totalResults)
{
$this->totalResults = $totalResults;
return $this;
}
}
$queryParameters = array_merge($this->parameters->getQueryParameters(), ['paginate' => $page]);
/** @var PagingResultSet $results */
$results = $this->query
->getContent("$contentType/pager", $queryParameters)
->get($contentType);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment