54 خطوط
1.8 KiB
PHP
54 خطوط
1.8 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Responses;
|
|
|
|
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Support\Str;
|
|
|
|
final class ApiResponse
|
|
{
|
|
public static function success(mixed $data, int $status = 200, ?string $message = null, array $meta = [], array $links = []): JsonResponse
|
|
{
|
|
return response()->json([
|
|
'data' => $data,
|
|
'meta' => (object) $meta,
|
|
'links' => (object) $links,
|
|
'message' => $message,
|
|
], $status);
|
|
}
|
|
|
|
public static function paginated(LengthAwarePaginator $paginator, callable $transformer): JsonResponse
|
|
{
|
|
return self::success(
|
|
collect($paginator->items())->map($transformer)->values()->all(),
|
|
meta: [
|
|
'current_page' => $paginator->currentPage(),
|
|
'last_page' => $paginator->lastPage(),
|
|
'per_page' => $paginator->perPage(),
|
|
'total' => $paginator->total(),
|
|
'from' => $paginator->firstItem(),
|
|
'to' => $paginator->lastItem(),
|
|
],
|
|
links: [
|
|
'first' => $paginator->url(1),
|
|
'last' => $paginator->url($paginator->lastPage()),
|
|
'prev' => $paginator->previousPageUrl(),
|
|
'next' => $paginator->nextPageUrl(),
|
|
],
|
|
);
|
|
}
|
|
|
|
public static function error(string $message, string $code, int $status, array $errors = [], ?string $traceId = null): JsonResponse
|
|
{
|
|
$traceId ??= (string) Str::uuid();
|
|
|
|
return response()->json([
|
|
'message' => $message,
|
|
'code' => $code,
|
|
'errors' => (object) $errors,
|
|
'trace_id' => $traceId,
|
|
], $status)->header('X-Trace-ID', $traceId);
|
|
}
|
|
}
|