Forked from peterjmit/doctrine_native_pagination.php
Last active
March 30, 2017 07:11
-
-
Save wilensky/49a2d853e06b0ac0cfed32d04bd4f4bc to your computer and use it in GitHub Desktop.
Helper function for paginating with PHP7 and native Doctrine class
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 | |
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