refactor:用 AdminApiList 统一后台列表类接口的响应格式
This commit is contained in:
75
app/Support/AdminApiList.php
Normal file
75
app/Support/AdminApiList.php
Normal file
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* 后台标准列表:`items` + `meta`(current_page / per_page / total / last_page)。
|
||||
* 供各 Admin Index 控制器复用,避免重复拼装分页 JSON。
|
||||
*/
|
||||
final class AdminApiList
|
||||
{
|
||||
public const DEFAULT_PER_PAGE = 25;
|
||||
|
||||
public const MAX_PER_PAGE = 100;
|
||||
|
||||
/**
|
||||
* 读取 `page`、`per_page`,并夹在 [1, maxPerPage]。
|
||||
*
|
||||
* @return array{page: int, perPage: int}
|
||||
*/
|
||||
public static function readPaging(Request $request, int $defaultPerPage = self::DEFAULT_PER_PAGE, int $maxPerPage = self::MAX_PER_PAGE): array
|
||||
{
|
||||
$perPage = min(max((int) $request->integer('per_page', $defaultPerPage), 1), $maxPerPage);
|
||||
$page = max((int) $request->integer('page', 1), 1);
|
||||
|
||||
return ['page' => $page, 'perPage' => $perPage];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param callable(object): array<string, mixed> $row
|
||||
* @return array{items: list<array<string, mixed>>, meta: array{current_page: int, per_page: int, total: int, last_page: int}}
|
||||
*/
|
||||
public static function payload(LengthAwarePaginator $paginator, callable $row): array
|
||||
{
|
||||
return [
|
||||
'items' => collect($paginator->items())->map($row)->values()->all(),
|
||||
'meta' => self::meta($paginator),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{current_page: int, per_page: int, total: int, last_page: int}
|
||||
*/
|
||||
public static function meta(LengthAwarePaginator $paginator): array
|
||||
{
|
||||
return [
|
||||
'current_page' => $paginator->currentPage(),
|
||||
'per_page' => $paginator->perPage(),
|
||||
'total' => $paginator->total(),
|
||||
'last_page' => $paginator->lastPage(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param callable(object): array<string, mixed> $row
|
||||
*/
|
||||
public static function json(LengthAwarePaginator $paginator, callable $row): JsonResponse
|
||||
{
|
||||
return ApiResponse::success(self::payload($paginator, $row));
|
||||
}
|
||||
|
||||
/**
|
||||
* 在标准列表外包一层字段(如 draw_id、job_no),与 items、meta 同级合并。
|
||||
*
|
||||
* @param callable(object): array<string, mixed> $row
|
||||
* @param array<string, mixed> $extra
|
||||
*/
|
||||
public static function jsonWith(LengthAwarePaginator $paginator, callable $row, array $extra = []): JsonResponse
|
||||
{
|
||||
return ApiResponse::success(array_merge($extra, self::payload($paginator, $row)));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user