Skip to content

Instantly share code, notes, and snippets.

@imiroslavov
Created July 4, 2019 07:42
Show Gist options
  • Save imiroslavov/f2038b87a800aa5ec3249e4d0d630380 to your computer and use it in GitHub Desktop.
Save imiroslavov/f2038b87a800aa5ec3249e4d0d630380 to your computer and use it in GitHub Desktop.
<?php
namespace App\Doctrine\ORM\Tools\Pagination;
use Doctrine\ORM\Tools\Pagination\Paginator as BasePaginator;
/**
* Class Paginator.
*/
class Paginator extends BasePaginator
{
/**
* @var int
*/
protected $page = 1;
/**
* @var int
*/
protected $limit;
const RESULTS_PER_PAGE = 10;
/**
* Paginator constructor.
*
* @param $query
* @param bool $fetchJoinCollection
* @param int $resultsPerPage
*/
public function __construct($query, $fetchJoinCollection = true, $resultsPerPage = self::RESULTS_PER_PAGE)
{
parent::__construct($query, $fetchJoinCollection);
$this->limit = $resultsPerPage;
}
/**
* @param int $page
* @param int $limit
*
* @return Paginator
*/
public function paginate($page, $limit = null): self
{
$page = max(1, $page);
if (null !== $limit) {
$this->limit = $limit;
}
$this->page = min($page, $this->getTotalPagesCount());
return $this;
}
/**
* @return int
*/
public function getPage(): int
{
return $this->page;
}
/**
* @return int
*/
public function getLimit(): int
{
return $this->limit;
}
/**
* @return int
*/
public function getTotalPagesCount(): int
{
return (int) ceil($this->count() / $this->getLimit());
}
/**
* @return bool
*/
public function hasResults(): bool
{
return 1 < $this->getTotalPagesCount();
}
/**
* @return bool
*/
public function canPaginate(): bool
{
return $this->page < $this->getTotalPagesCount();
}
/**
* @throws \Doctrine\Common\Persistence\Mapping\MappingException
*
* @return \Iterator
*/
public function getIterator(): \Iterator
{
$this->getQuery()->setMaxResults($this->getLimit());
$this->getQuery()->setFirstResult($this->getFirstResult());
foreach (parent::getIterator() as $result) {
yield $result;
}
}
/**
* @return mixed
*/
private function getFirstResult()
{
return max(0, ($this->getLimit() * ($this->getPage() - 1)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment