Files
Ecobuddy/Models/Paginator.php
boris 4005328979 erm did a small amount
output database to view
added basic filters
improve bootstrap theming and positioning
added pagination
2024-11-28 23:40:06 +00:00

84 lines
2.7 KiB
PHP

<?php
require_once('FacilityDataSet.php');
class Paginator {
protected $_pages, $_totalPages, $_rowLimit, $_offset, $_pageMatrix, $_rowCount;
public function __construct($rowLimit, $offset, $dataset) {
$this->_rowLimit = $rowLimit;
$this->_offset = $offset;
$this->_totalPages = $this->calculateTotalPages($dataset['count']);
$this->_rowCount = $dataset['count'];
$this->_pages = $dataset['dataset'];
$this->_pageMatrix = $this->Paginate();
}
private function calculateTotalPages(int $count): int {
return $count > 0 ? ceil($count / $this->_rowLimit) : 0;
}
public function Paginate(): array {
$pageMatrix = [];
for ($i = 0; $i < $this->_totalPages; $i++) {
$page = [];
$start = $i * $this->_rowLimit;
$end = min($start + $this->_rowLimit, $this->_rowCount); // Ensure within bounds
for ($j = $start; $j < $end; $j++) {
$page[] = $this->_pages[$j];
}
$pageMatrix[$i] = $page;
}
return $pageMatrix;
}
function getPageFromUri(): int {
// Retrieve 'page' parameter and default to 0 if missing or invalid
return filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT, [
'options' => ['default' => 0, 'min_range' => 0] // Default to 0 if invalid or missing
]);
}
public function setPageUri(int $page): void
{
$uri = $_SERVER['REQUEST_URI'];
$uriComp = parse_url($uri);
$params = [];
// Parse existing query parameters
if (isset($uriComp['query'])) {
parse_str($uriComp['query'], $params);
}
// Avoid unnecessary redirection if the page is already correct
if (isset($params['page']) && (int)$params['page'] === $page) {
return; // Do nothing if already on the correct page
}
// Update the 'page' parameter
$params['page'] = $page;
// Rebuild the query string
$newUri = http_build_query($params);
// Redirect to the updated URI
$path = $uriComp['path'] ?? '/'; // Use the current path or root
header("Location: $path?$newUri");
exit;
}
public function getPage(int $pageNumber): array {
if ($pageNumber < 0 || $pageNumber >= $this->_totalPages) {
return []; // Return an empty array if the page number is invalid
}
return $this->_pageMatrix[$pageNumber];
}
public function countPageResults(int $pageNumber): int {
if ($pageNumber < 0 || $pageNumber >= $this->_totalPages) {
return 0; // Return 0 if the page number is invalid
}
return count($this->_pageMatrix[$pageNumber]);
}
}