Completed
Push — master ( 580028...d7e9e8 )
by Charles
02:19
created

JsonResponseFormatter   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 12
c 1
b 0
f 0
lcom 1
cbo 5
dl 0
loc 62
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
C formatJson() 0 55 12
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
}