Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save wilensky/49a2d853e06b0ac0cfed32d04bd4f4bc to your computer and use it in GitHub Desktop.
Save wilensky/49a2d853e06b0ac0cfed32d04bd4f4bc to your computer and use it in GitHub Desktop.
Helper function for paginating with PHP7 and native Doctrine class
<?php
use Doctrine\ORM\Query;
use Doctrine\ORM\Tools\Pagination\Paginator;
// ------------------- //
public function paginate(Query $query, int $page = 1, int $limit = 10, bool $fetchJoinCollection = true)
{
// If we don't have a limit just return the result
if ($page === 1 && $limit === 0) {
return $query->getResult();
}
$paginator = new Paginator(
$query->setFirstResult(($page * $limit) - $limit) // Offset
->setMaxResults($limit), // Limit
$fetchJoinCollection
);
// Num results
$count = $paginator->count();
return [
'result' => $paginator->getIterator()->getArrayCopy(),// `getArrayCopy()` for to be passed to `array_map()` directly
'meta' => [
'total' => (int)$count,
'page' => (int)$page,
'pages' => (int)ceil($count / $limit)
]
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment