Conditions | 12 |
Paths | 41 |
Total Lines | 55 |
Code Lines | 31 |
Lines | 0 |
Ratio | 0 % |
Changes | 1 | ||
Bugs | 0 | Features | 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 |
||
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 | } |