Skip to content

Instantly share code, notes, and snippets.

@Sammyjo20
Last active August 6, 2022 00:15
Show Gist options
  • Save Sammyjo20/3a06e26528ca7c3413ae40a65589d644 to your computer and use it in GitHub Desktop.
Save Sammyjo20/3a06e26528ca7c3413ae40a65589d644 to your computer and use it in GitHub Desktop.
API Paginator
<?php
namespace App\Data;
class Paginator
{
/**
* Constructor
*
* @param int $totalPages
* @param int $perPage
* @param int $currentPage
* @param int $currentOffset
*/
public function __construct(
public int $totalPages,
public int $perPage,
public int $currentPage = 1,
public int $currentOffset = 0,
)
{
//
}
/**
* Create a new paginator.
*
* @param int $total
* @param int $perPage
* @return static
*/
public static function create(int $total, int $perPage): static
{
$totalPages = (int)round($total / $perPage);
if ($totalPages < 1) {
$totalPages = 1;
}
return new static ($totalPages, $perPage);
}
/**
* Check if on the final page.
*
* @return bool
*/
public function onFinalPage(): bool
{
if ($this->currentPage >= $this->totalPages) {
return true;
}
if ($this->currentPage === 1 && $this->totalPages === 1) {
return true;
}
return false;
}
/**
* Go to the next page.
*
* @return $this
*/
public function nextPage(): static
{
if ($this->onFinalPage()) {
return $this;
}
$this->currentPage++;
$this->currentOffset += $this->perPage;
return $this;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment