|
1
|
|
|
<?php declare(strict_types=1); |
|
2
|
|
|
|
|
3
|
|
|
namespace yrc\web; |
|
4
|
|
|
|
|
5
|
|
|
use yii\helpers\Json; |
|
6
|
|
|
use Yii; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* Handles formatting of the response |
|
10
|
|
|
* @class JsonResponseFormatter |
|
11
|
|
|
*/ |
|
12
|
|
|
class JsonResponseFormatter extends \yii\web\JsonResponseFormatter |
|
13
|
|
|
{ |
|
14
|
|
|
/** |
|
15
|
|
|
* Formats response data in JSON format. |
|
16
|
|
|
* @param Response $response |
|
17
|
|
|
*/ |
|
18
|
|
|
protected function formatJson($response) |
|
19
|
|
|
{ |
|
20
|
|
|
$response->getHeaders()->set('Content-Type', 'application/json; charset=UTF-8'); |
|
21
|
|
|
if ($response->data !== null) { |
|
22
|
|
|
$options = $this->encodeOptions; |
|
23
|
|
|
if ($this->prettyPrint) { |
|
24
|
|
|
$options |= JSON_PRETTY_PRINT; |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
$status = 200; |
|
28
|
|
|
|
|
29
|
|
|
// Pull the exception |
|
30
|
|
|
if ($exception = Yii::$app->errorHandler->exception) { |
|
31
|
|
|
if (is_a($exception, 'yii\web\HttpException')) { |
|
32
|
|
|
$copy = $response->data; |
|
33
|
|
|
|
|
34
|
|
|
if (isset($copy['message'])) { |
|
35
|
|
|
$message = \json_decode($copy['message']); |
|
36
|
|
|
if (\json_last_error() === JSON_ERROR_NONE) { |
|
37
|
|
|
$copy['message'] = $message; |
|
38
|
|
|
} |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
$response->data = [ |
|
42
|
|
|
'data' => null, |
|
43
|
|
|
'error' => [ |
|
44
|
|
|
'message' => $copy['message'], |
|
45
|
|
|
'code' => $copy['code'] |
|
46
|
|
|
] |
|
47
|
|
|
]; |
|
48
|
|
|
|
|
49
|
|
|
$status = $copy['status']; |
|
50
|
|
|
} else { |
|
51
|
|
|
Yii::error([ |
|
52
|
|
|
'message' => 'A fatal uncaught error occured.', |
|
53
|
|
|
'exception' => $exception |
|
54
|
|
|
]); |
|
55
|
|
|
$status = 500; |
|
56
|
|
|
$response->data = [ |
|
57
|
|
|
'data' => null, |
|
58
|
|
|
'error' => [ |
|
59
|
|
|
'message' => Yii::t('yrc', 'An unexpected error occured.'), |
|
60
|
|
|
'code' => 0 |
|
61
|
|
|
] |
|
62
|
|
|
]; |
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
if (\is_object($response->data)) { |
|
67
|
|
|
$copy = $response->data; |
|
68
|
|
|
$response->data = null; |
|
69
|
|
|
$response->data['data'] = $copy; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
if (!\is_array($response->data) || (is_array($response->data) && !array_key_exists('data', $response->data))) { |
|
73
|
|
|
$copy = $response->data; |
|
74
|
|
|
|
|
75
|
|
|
$error = $copy['error'] ?? null; |
|
76
|
|
|
unset($copy['error']); |
|
77
|
|
|
if ($error !== null) { |
|
78
|
|
|
$response->data['error'] = $error; |
|
79
|
|
|
} |
|
80
|
|
|
|
|
81
|
|
|
$response->data = [ |
|
82
|
|
|
'data' => $copy, |
|
83
|
|
|
'error' => null |
|
84
|
|
|
]; |
|
85
|
|
|
} |
|
86
|
|
|
|
|
87
|
|
|
$response->data['status'] = $status; |
|
88
|
|
|
$response->content = Json::encode($response->data, $options); |
|
89
|
|
|
} |
|
90
|
|
|
} |
|
91
|
|
|
} |
|
92
|
|
|
|