71 lines
1.8 KiB
PHP
71 lines
1.8 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Support;
|
|
|
|
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
|
use Illuminate\Http\JsonResponse;
|
|
use stdClass;
|
|
|
|
final class ApiResponse
|
|
{
|
|
public const DEFAULT_PER_PAGE = 20;
|
|
|
|
public const MAX_PER_PAGE = 100;
|
|
|
|
public static function success(mixed $data = null, string $message = 'OK', int $status = 200): JsonResponse
|
|
{
|
|
return response()->json([
|
|
'success' => true,
|
|
'message' => $message,
|
|
'data' => $data,
|
|
], $status);
|
|
}
|
|
|
|
/**
|
|
* @param array<string, mixed> $errors
|
|
*/
|
|
public static function failure(string $message, array $errors = [], int $status = 400): JsonResponse
|
|
{
|
|
return response()->json([
|
|
'success' => false,
|
|
'message' => $message,
|
|
'errors' => $errors === [] ? new stdClass : $errors,
|
|
], $status);
|
|
}
|
|
|
|
/**
|
|
* @param LengthAwarePaginator<int, mixed> $paginator
|
|
*/
|
|
public static function paginated(LengthAwarePaginator $paginator, string $message = 'OK'): JsonResponse
|
|
{
|
|
return response()->json([
|
|
'success' => true,
|
|
'message' => $message,
|
|
'data' => array_values($paginator->items()),
|
|
'meta' => [
|
|
'current_page' => $paginator->currentPage(),
|
|
'per_page' => $paginator->perPage(),
|
|
'total' => $paginator->total(),
|
|
'last_page' => $paginator->lastPage(),
|
|
],
|
|
]);
|
|
}
|
|
|
|
public static function perPage(mixed $requested): int
|
|
{
|
|
if (! is_numeric($requested)) {
|
|
return self::DEFAULT_PER_PAGE;
|
|
}
|
|
|
|
$pageSize = (int) $requested;
|
|
|
|
if ($pageSize < 1) {
|
|
return self::DEFAULT_PER_PAGE;
|
|
}
|
|
|
|
return min($pageSize, self::MAX_PER_PAGE);
|
|
}
|
|
}
|