1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace Sarala\Exceptions; |
||
6 | |||
7 | use Exception; |
||
8 | use Illuminate\Http\JsonResponse; |
||
9 | use Illuminate\Http\Request; |
||
10 | |||
11 | abstract class ApiException extends Exception implements JsonApiExceptionContract |
||
12 | { |
||
13 | /** |
||
14 | * Get unique identifier for this particular occurrence |
||
15 | * of the problem. |
||
16 | */ |
||
17 | public function id(): string |
||
18 | { |
||
19 | return ''; |
||
20 | } |
||
21 | |||
22 | /** |
||
23 | * Get application-specific error code. |
||
24 | */ |
||
25 | public function code(): string |
||
26 | { |
||
27 | return ''; |
||
28 | } |
||
29 | |||
30 | /** |
||
31 | * Get human-readable explanation specific to this |
||
32 | * occurrence of the problem. |
||
33 | */ |
||
34 | public function detail(): string |
||
35 | { |
||
36 | return ''; |
||
37 | } |
||
38 | |||
39 | /** |
||
40 | * Get the URI that yield further details about this |
||
41 | * particular occurrence of the problem. |
||
42 | */ |
||
43 | public function href(): string |
||
44 | { |
||
45 | return ''; |
||
46 | } |
||
47 | |||
48 | /** |
||
49 | * Get associated resources, which can be dereferenced |
||
50 | * from the request document. |
||
51 | */ |
||
52 | public function links(): array |
||
53 | { |
||
54 | return []; |
||
55 | } |
||
56 | |||
57 | /** |
||
58 | * Get relative path to the relevant attribute within |
||
59 | * the associated resource(s). |
||
60 | */ |
||
61 | public function path(): string |
||
62 | { |
||
63 | return ''; |
||
64 | } |
||
65 | |||
66 | /** |
||
67 | * Get non-standard meta-information about the error. |
||
68 | */ |
||
69 | public function meta(): array |
||
70 | { |
||
71 | return []; |
||
72 | } |
||
73 | |||
74 | protected function getResponseData(): array |
||
75 | { |
||
76 | $error = array_merge([ |
||
77 | 'status' => (string) $this->status(), |
||
78 | 'title' => $this->title(), |
||
79 | ], $this->getAvailableData()); |
||
80 | |||
81 | return [ |
||
82 | 'errors' => [$error], |
||
83 | ]; |
||
84 | } |
||
85 | |||
86 | protected function getApiResponse(): JsonResponse |
||
87 | { |
||
88 | return response() |
||
89 | ->json($this->getResponseData(), $this->status()); |
||
90 | } |
||
91 | |||
92 | public function render(Request $request): JsonResponse |
||
93 | { |
||
94 | return $this->getApiResponse(); |
||
95 | } |
||
96 | |||
97 | private function getAvailableData(): array |
||
98 | { |
||
99 | $data = []; |
||
100 | |||
101 | collect(['links', 'meta', 'id', 'href', 'code', 'detail', 'path'])->each(function ($key) use (&$data) { |
||
0 ignored issues
–
show
Bug
introduced
by
![]() |
|||
102 | if (! empty($this->{$key}())) { |
||
103 | $data[$key] = $this->{$key}(); |
||
104 | } |
||
105 | }); |
||
106 | |||
107 | return $data; |
||
108 | } |
||
109 | } |
||
110 |