misuzu/src/Pagination.php

74 lines
1.8 KiB
PHP

<?php
namespace Misuzu;
use Index\Http\HttpRequest;
final class Pagination {
public private(set) bool $validOffset;
public function __construct(
public private(set) int $count = 0,
public private(set) int $range = 0,
public private(set) int $offset = 0
) {
$this->count = max(0, $count);
if($range < 1)
$this->range = $count;
$this->validOffset = $offset >= 0 && $offset < $count;
$this->offset = max(0, $offset);
}
public int $pages {
get => (int)ceil($this->count / $this->range);
}
public int $page {
get => (int)floor($this->offset / $this->range) + 1;
}
public static function fromPage(
int $count,
int $page,
int $range = 0,
int $firstPage = 1
): self {
if($range < 1)
$range = $count;
$offset = $range * ($page - $firstPage);
if($offset < 0 || $offset >= $count)
$offset = -1;
return new Pagination($count, $range, $offset);
}
public static function fromInput(
int $count,
int $range = 0,
string $pageParam = 'p',
int $firstPage = 1
): self {
return self::fromPage(
$count,
(int)(filter_input(INPUT_GET, $pageParam, FILTER_SANITIZE_NUMBER_INT) ?? $firstPage),
$range,
$firstPage
);
}
public static function fromRequest(
HttpRequest $request,
int $count,
int $range = 0,
string $pageParam = 'page',
int $firstPage = 1
): Pagination {
return self::fromPage(
$count,
(int)($request->getParam($pageParam, FILTER_SANITIZE_NUMBER_INT) ?? $firstPage),
$range,
$firstPage
);
}
}