1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace App\Ship\Exceptions\Formatters; |
4
|
|
|
|
5
|
|
|
use Apiato\Core\Exceptions\Formatters\ExceptionsFormatter as CoreExceptionsFormatter; |
6
|
|
|
use Exception; |
7
|
|
|
use Illuminate\Http\JsonResponse; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Class UnprocessableEntityHttpExceptionFormatter |
11
|
|
|
* |
12
|
|
|
* @author Johannes Schobel <[email protected]> |
13
|
|
|
* @author Mahmoud Zalt <[email protected]> |
14
|
|
|
*/ |
15
|
|
|
class UnprocessableEntityHttpExceptionFormatter extends CoreExceptionsFormatter |
16
|
|
|
{ |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Status Code. |
20
|
|
|
* |
21
|
|
|
* @var int |
22
|
|
|
*/ |
23
|
|
|
CONST STATUS_CODE = 422; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @param \Exception $exception |
27
|
|
|
* @param \Illuminate\Http\JsonResponse $response |
28
|
|
|
* |
29
|
|
|
* @return array |
30
|
|
|
*/ |
31
|
|
|
public function responseData(Exception $exception, JsonResponse $response) |
32
|
|
|
{ |
33
|
|
|
// Laravel validation errors will return JSON string |
34
|
|
|
$decoded = json_decode($exception->getMessage(), true); |
35
|
|
|
// Message was not valid JSON |
36
|
|
|
// This occurs when we throw UnprocessableEntityHttpExceptions |
37
|
|
|
if (json_last_error() !== JSON_ERROR_NONE) { |
38
|
|
|
// Mimic the structure of Laravel validation errors |
39
|
|
|
$decoded = [[$exception->getMessage()]]; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
// Laravel errors are formatted as {"field": [/*errors as strings*/]} |
43
|
|
|
$responseData = array_reduce($decoded, function ($carry, $item) use ($exception) { |
44
|
|
|
return array_merge($carry, array_map(function ($current) use ($exception) { |
45
|
|
|
return [ |
46
|
|
|
'status' => self::STATUS_CODE, |
47
|
|
|
'code' => $exception->getCode(), |
48
|
|
|
'title' => 'Validation error', |
49
|
|
|
'detail' => $current |
50
|
|
|
]; |
51
|
|
|
}, $item)); |
52
|
|
|
}, []); |
53
|
|
|
|
54
|
|
|
return [ |
55
|
|
|
'code' => $exception->getCode(), |
56
|
|
|
'message' => $exception->getMessage(), |
57
|
|
|
'errors' => $responseData, |
58
|
|
|
]; |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @param \Exception $exception |
64
|
|
|
* @param \Illuminate\Http\JsonResponse $response |
65
|
|
|
* |
66
|
|
|
* @return mixed |
67
|
|
|
*/ |
68
|
|
|
function modifyResponse(Exception $exception, JsonResponse $response) |
|
|
|
|
69
|
|
|
{ |
70
|
|
|
return $response; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* @return int |
75
|
|
|
*/ |
76
|
|
|
public function statusCode() |
77
|
|
|
{ |
78
|
|
|
return self::STATUS_CODE; |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
|
82
|
|
|
} |
83
|
|
|
|
Adding explicit visibility (
private
,protected
, orpublic
) is generally recommend to communicate to other developers how, and from where this method is intended to be used.