1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace yrc\web; |
4
|
|
|
|
5
|
|
|
use yii\helpers\Json; |
6
|
|
|
use yii\web\JsonResponseFormatter as YiiJsonResponseFormatter; |
7
|
|
|
use Yii; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Handles formatting of the response |
11
|
|
|
* @class JsonResponseFormatter |
12
|
|
|
*/ |
13
|
|
|
class JsonResponseFormatter extends YiiJsonResponseFormatter |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* Formats response data in JSON format. |
17
|
|
|
* @param Response $response |
18
|
|
|
*/ |
19
|
|
|
protected function formatJson($response) |
20
|
|
|
{ |
21
|
|
|
$response->getHeaders()->set('Content-Type', 'application/json; charset=UTF-8'); |
22
|
|
|
if ($response->data !== null) { |
23
|
|
|
$options = $this->encodeOptions; |
24
|
|
|
if ($this->prettyPrint) { |
25
|
|
|
$options |= JSON_PRETTY_PRINT; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
$status = 200; |
29
|
|
|
|
30
|
|
|
// Pull the exception |
31
|
|
|
$exception = Yii::$app->errorHandler->exception; |
32
|
|
|
if ($exception && is_subclass_of($exception, 'yii\web\HttpException') || get_class($exception) === 'yii\web\HttpException' ) { |
33
|
|
|
$copy = $response->data; |
34
|
|
|
$response->data = null; |
35
|
|
|
|
36
|
|
|
if (isset($copy['message'])) { |
37
|
|
|
$message = \json_decode($copy['message']); |
38
|
|
|
if (\json_last_error() === JSON_ERROR_NONE) { |
39
|
|
|
$copy['message'] = $message; |
40
|
|
|
} |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
$response->data['error'] = [ |
44
|
|
|
'message' => $copy['message'], |
45
|
|
|
'code' => $copy['code'] |
46
|
|
|
]; |
47
|
|
|
|
48
|
|
|
$status = $copy['status']; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
// If the data attribute isn't set, transfer everything into it and build the new response object |
52
|
|
|
if (!isset($response->data['data'])) { |
53
|
|
|
$copy = $response->data; |
54
|
|
|
|
55
|
|
|
$error = $copy['error'] ?? null; |
56
|
|
|
unset($copy['error']); |
57
|
|
|
|
58
|
|
|
$response->data = null; |
59
|
|
|
$response->data['data'] = $copy; |
60
|
|
|
if ($error !== null) { |
61
|
|
|
$response->data['error'] = $error; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
$response->data['status'] = $status; |
65
|
|
|
|
66
|
|
|
if ($response->data['data'] === [] || $response->data['data'] === null) { |
67
|
|
|
$response->data['data'] = null; |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
$response->content = Json::encode($response->data, $options); |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
} |