/DataPaginator.php Secret
Created
May 28, 2021 10:20
API Platform - Custom resource Data paginator
This file contains hidden or 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 | |
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