Pagination.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536
  1. <?php
  2. declare(strict_types=1);
  3. namespace app\miniapi\http;
  4. final class Pagination
  5. {
  6. public readonly int $page;
  7. public readonly int $pageSize;
  8. public function __construct(array $query)
  9. {
  10. $this->page = Input::integer($query['page'] ?? 1, 'page', 1, 1000000);
  11. $this->pageSize = Input::integer($query['page_size'] ?? config('mini_api.default_page_size', 20), 'page_size', 1, (int) config('mini_api.max_page_size', 100));
  12. if (config('mini_protection.enabled', false) && $this->offset() >= (int) config('mini_protection.max_list_offset', 10000)) {
  13. throw new \app\miniapi\exception\ApiException(42201, '查询范围过大,请缩小筛选范围', 422, ['page' => '超出允许的分页查询范围']);
  14. }
  15. }
  16. public function offset(): int
  17. {
  18. return ($this->page - 1) * $this->pageSize;
  19. }
  20. public function result(array $items, int $total): array
  21. {
  22. return [
  23. 'items' => array_values($items),
  24. 'total' => $total,
  25. 'page' => $this->page,
  26. 'page_size' => $this->pageSize,
  27. 'has_more' => $this->offset() + count($items) < $total,
  28. ];
  29. }
  30. }