Last active
August 6, 2022 00:15
-
-
Save Sammyjo20/3a06e26528ca7c3413ae40a65589d644 to your computer and use it in GitHub Desktop.
API 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\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