- Parser additions, pagination
This commit is contained in:
@@ -79,11 +79,12 @@ final class ContentRepository
|
||||
return $item;
|
||||
}
|
||||
|
||||
/** @return array{items: array<int, array<string, mixed>>, pagination: array<string, int|bool|null>} */
|
||||
/** @return array{items: array<int, array<string, mixed>>, pagination: array<string, mixed>} */
|
||||
public function paginate(array $items, int $page, int $perPage): array
|
||||
{
|
||||
$perPage = max(1, $perPage);
|
||||
$total = count($items);
|
||||
$pages = max(1, (int) ceil($total / max(1, $perPage)));
|
||||
$pages = max(1, (int) ceil($total / $perPage));
|
||||
$page = max(1, min($page, $pages));
|
||||
$offset = ($page - 1) * $perPage;
|
||||
|
||||
@@ -98,11 +99,12 @@ final class ContentRepository
|
||||
'has_next' => $page < $pages,
|
||||
'previous' => $page > 1 ? $page - 1 : null,
|
||||
'next' => $page < $pages ? $page + 1 : null,
|
||||
'numbers' => $this->paginationNumbers($page, $pages, 10),
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array{items: array<int, array<string, mixed>>, pagination: array<string, int|bool|null>} */
|
||||
/** @return array{items: array<int, array<string, mixed>>, pagination: array<string, mixed>} */
|
||||
public function search(string $query, int $page, int $perPage): array
|
||||
{
|
||||
$query = trim(mb_strtolower($query));
|
||||
@@ -150,6 +152,27 @@ final class ContentRepository
|
||||
return $this->paginate($scored, $page, $perPage);
|
||||
}
|
||||
|
||||
/** @return array<int, int> */
|
||||
private function paginationNumbers(int $page, int $pages, int $window): array
|
||||
{
|
||||
if ($pages <= 1) {
|
||||
return [1];
|
||||
}
|
||||
if ($pages <= $window) {
|
||||
return range(1, $pages);
|
||||
}
|
||||
|
||||
$before = (int) floor(($window - 1) / 2);
|
||||
$start = max(1, $page - $before);
|
||||
$end = $start + $window - 1;
|
||||
if ($end > $pages) {
|
||||
$end = $pages;
|
||||
$start = max(1, $end - $window + 1);
|
||||
}
|
||||
|
||||
return range($start, $end);
|
||||
}
|
||||
|
||||
/** @return array<int, array<string, mixed>> */
|
||||
public function byCategory(string $categorySlug): array
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user