Files
lotteryLaravel/app/Support/PaginationTrait.php

52 lines
1.3 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
declare(strict_types=1);
namespace App\Support;
use Illuminate\Http\Request;
/**
* 分页请求参数解析 trait。
*
* 统一处理 `page`、`per_page`/`size` 参数的合法化。
*/
trait PaginationTrait
{
/**
* 解析并限制每页条数。
*
* @param Request $request 请求对象
* @param string $key 参数名(默认 per_page
* @param int $default 默认值
* @param int $max 最大值上限
*/
protected function perPage(Request $request, string $key = 'per_page', int $default = 10, int $max = 50): int
{
$value = (int) $request->query($key, $request->query('size', $default));
return max(1, min($max, $value));
}
/**
* 解析当前页码(强制至少为 1
*/
protected function page(Request $request, string $key = 'page', int $default = 1): int
{
return max(1, (int) $request->query($key, $default));
}
/**
* 解析分页元数据数组。
*
* @return array{page: int, per_page: int}
*/
protected function paginationMeta(Request $request, int $defaultPerPage = 10, int $maxPerPage = 50): array
{
return [
'page' => $this->page($request),
'per_page' => $this->perPage($request, 'per_page', $defaultPerPage, $maxPerPage),
];
}
}