Conditions | 12 |
Paths | 61 |
Total Lines | 71 |
Code Lines | 44 |
Lines | 0 |
Ratio | 0 % |
Changes | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | <?php declare(strict_types=1); |
||
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 | } |
||
92 |