2019-01-03 01:33:02 +01:00
|
|
|
<?php
|
2019-12-06 02:04:10 +01:00
|
|
|
namespace Misuzu;
|
2019-01-03 01:33:02 +01:00
|
|
|
|
2024-12-19 01:22:26 +00:00
|
|
|
use Index\Http\HttpRequest;
|
2019-01-03 01:33:02 +01:00
|
|
|
|
2024-12-19 01:22:26 +00:00
|
|
|
final class Pagination {
|
|
|
|
public private(set) bool $validOffset;
|
2019-01-03 01:33:02 +01:00
|
|
|
|
2024-12-19 01:22:26 +00:00
|
|
|
public function __construct(
|
|
|
|
public private(set) int $count = 0,
|
|
|
|
public private(set) int $range = 0,
|
|
|
|
public private(set) int $offset = 0
|
|
|
|
) {
|
2020-05-16 22:35:11 +00:00
|
|
|
$this->count = max(0, $count);
|
2024-12-19 01:22:26 +00:00
|
|
|
if($range < 1)
|
|
|
|
$this->range = $count;
|
2019-01-03 01:33:02 +01:00
|
|
|
|
2024-12-19 01:22:26 +00:00
|
|
|
$this->validOffset = $offset >= 0 && $offset < $count;
|
|
|
|
$this->offset = max(0, $offset);
|
2019-12-06 02:04:10 +01:00
|
|
|
}
|
2019-01-03 01:33:02 +01:00
|
|
|
|
2024-12-19 01:22:26 +00:00
|
|
|
public int $pages {
|
|
|
|
get => (int)ceil($this->count / $this->range);
|
2019-01-03 01:33:02 +01:00
|
|
|
}
|
|
|
|
|
2024-12-19 01:22:26 +00:00
|
|
|
public int $page {
|
|
|
|
get => (int)floor($this->offset / $this->range) + 1;
|
2019-12-06 02:04:10 +01:00
|
|
|
}
|
2019-01-03 01:33:02 +01:00
|
|
|
|
2024-12-19 01:22:26 +00:00
|
|
|
public static function fromPage(
|
|
|
|
int $count,
|
|
|
|
int $page,
|
|
|
|
int $range = 0,
|
|
|
|
int $firstPage = 1
|
|
|
|
): self {
|
|
|
|
if($range < 1)
|
|
|
|
$range = $count;
|
2019-01-03 01:33:02 +01:00
|
|
|
|
2024-12-19 01:22:26 +00:00
|
|
|
$offset = $range * ($page - $firstPage);
|
|
|
|
if($offset < 0 || $offset >= $count)
|
|
|
|
$offset = -1;
|
2019-12-06 02:04:10 +01:00
|
|
|
|
2024-12-19 01:22:26 +00:00
|
|
|
return new Pagination($count, $range, $offset);
|
2019-03-18 23:02:30 +01:00
|
|
|
}
|
|
|
|
|
2024-12-19 01:22:26 +00:00
|
|
|
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
|
|
|
|
);
|
2019-12-06 02:04:10 +01:00
|
|
|
}
|
|
|
|
|
2024-12-19 01:22:26 +00:00
|
|
|
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
|
|
|
|
);
|
2019-12-06 02:04:10 +01:00
|
|
|
}
|
2019-01-03 01:33:02 +01:00
|
|
|
}
|