Skip to content

Instantly share code, notes, and snippets.

@bastien70
Created May 28, 2021 10:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bastien70/14e7f38db7268ff3bdbf18125b4e44e2 to your computer and use it in GitHub Desktop.
Save bastien70/14e7f38db7268ff3bdbf18125b4e44e2 to your computer and use it in GitHub Desktop.
API Platform - Custom resource Data paginator
<?php
namespace App\DataProvider;
use ApiPlatform\Core\DataProvider\PaginatorInterface;
class DataPaginator implements PaginatorInterface, \IteratorAggregate
{
private $iterator;
public function __construct(
private int $currentPage,
private int $maxResults,
private array $results, // here the results for current page (or maybe pass all results, and in this class, calculate results for current page ?
private ?float $totalItems = null // here, total items ($this->statsHelper->count() result function), or nothing
){}
public function getLastPage(): float
{
return ceil($this->getTotalItems() / $this->getItemsPerPage()) ?: 1.;
}
public function getTotalItems(): float
{
// instead of 'return $this->statsHelper->count(), use return $this->totalItems ?: count($this->results);
// if $this->totalItems is set, return it. Else, we estimate that $ this-> results contains all results and not just those of the current page
return $this->totalItems ?: count($this->results);
}
public function getCurrentPage(): float
{
return $this->currentPage;
}
public function getItemsPerPage(): float
{
return $this->maxResults;
}
public function count()
{
return iterator_count($this->getIterator());
}
public function getIterator()
{
if($this->iterator === null) {
// $offset = (($this->getCurrentPage() - 1) * $this->getItemsPerPage());
$this->iterator = new \ArrayIterator($this->results); //results for current page. Or maybe pass all results, and here, calculate for current page results ?
}
return $this->iterator;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment