File size: 1,190 Bytes
b2dcf0f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<?php

namespace App\Shared\Http;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ApiResponse
{
    public static function success(array $data = [], array $meta = [], int $status = 200): JsonResponse
    {
        return response()->json([
            'success' => true,
            'data' => $data,
            'meta' => self::withRequestId($meta),
        ], $status);
    }

    public static function error(string $code, string $message, array $details = [], int $status = 400): JsonResponse
    {
        return response()->json([
            'success' => false,
            'error' => [
                'code' => $code,
                'message' => $message,
                'details' => $details,
            ],
            'meta' => self::withRequestId(),
        ], $status);
    }

    private static function withRequestId(array $meta = []): array
    {
        $request = app()->bound('request') ? app(Request::class) : null;
        $requestId = $request?->attributes->get('request_id');

        if ($requestId !== null && ! array_key_exists('request_id', $meta)) {
            $meta['request_id'] = $requestId;
        }

        return $meta;
    }
}