78 lines
2.4 KiB
PHP
78 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace Itguild\Tables;
|
|
|
|
|
|
use Exception;
|
|
use http\Message;
|
|
|
|
class Pagination
|
|
{
|
|
|
|
private string $html = "";
|
|
private int $perPage = 10;
|
|
private int $countItem;
|
|
private int $currentPage = 1;
|
|
private int $countPages;
|
|
|
|
private string $baseUrl;
|
|
|
|
/**
|
|
* @throws Exception
|
|
*/
|
|
public function __construct(array $options)
|
|
{
|
|
if (!$options['countItem']) {
|
|
throw new Exception(message: "countItem is not valid");
|
|
}
|
|
$this->countItem = $options['countItem'];
|
|
$this->perPage = $options['perPage'] ?? 10;
|
|
$this->currentPage = $options['currentPage'] ?? 1;
|
|
$this->baseUrl = $options['baseUrl'] ?? '';
|
|
$this->baseUrl .= $options['prefix'] ?? '/page';
|
|
|
|
$this->countPages = ceil($this->countItem / $this->perPage);
|
|
}
|
|
|
|
public function create(): void
|
|
{
|
|
$prev = $this->currentPage - 1 >= 1 ? $this->currentPage - 1 : null;
|
|
$next = $this->currentPage + 1 <= $this->countPages ? $this->currentPage + 1 : null;
|
|
$btns = $prev ? "<li class='page-item'><a class='page-link' href='$this->baseUrl/$prev'>$prev</a></li>" : "";
|
|
$btns .= "<li class='page-item'><a class='page-link active' href='#'>$this->currentPage</a></li>";
|
|
$btns .= $next ? "<li class='page-item'><a class='page-link' href='$this->baseUrl/$next'>$next</a></li>" : "";
|
|
|
|
$this->html = str_replace('{btns}', $btns, $this->getTemplate());
|
|
$this->html = str_replace('{previous_link}', $this->baseUrl . "/1", $this->html);
|
|
$this->html = str_replace('{next_link}', $this->baseUrl . "/" . $this->countPages, $this->html);
|
|
}
|
|
|
|
public function render(): void
|
|
{
|
|
echo $this->html;
|
|
}
|
|
|
|
public function fetch(): string
|
|
{
|
|
return $this->html;
|
|
}
|
|
|
|
private function getTemplate(): string
|
|
{
|
|
return '<nav aria-label="Page navigation example">
|
|
<ul class="pagination">
|
|
<li class="page-item">
|
|
<a class="page-link" href="{previous_link}" aria-label="Previous">
|
|
<span aria-hidden="true">«</span>
|
|
</a>
|
|
</li>
|
|
{btns}
|
|
<li class="page-item">
|
|
<a class="page-link" href="{next_link}" aria-label="Next">
|
|
<span aria-hidden="true">»</span>
|
|
</a>
|
|
</li>
|
|
</ul>
|
|
</nav>';
|
|
}
|
|
} |