Passed
Push — master ( f763ca...75bce8 )
by Anton
01:09
created

JsonApiResponseFormatter::format()   C

Complexity

Conditions 12
Paths 36

Size

Total Lines 39
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 24
nc 36
nop 1
dl 0
loc 39
rs 6.9666
c 0
b 0
f 0

How to fix   Complexity   

Long Method

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:

1
<?php
2
/**
3
 * @author Anton Tuyakhov <[email protected]>
4
 */
5
6
namespace tuyakhov\jsonapi;
7
8
use yii\base\Component;
9
use yii\helpers\ArrayHelper;
10
use yii\helpers\Json;
11
use yii\helpers\Url;
12
use yii\web\ErrorHandler;
13
use yii\web\Link;
14
use yii\web\Response;
15
use yii\web\ResponseFormatterInterface;
16
17
class JsonApiResponseFormatter extends Component implements ResponseFormatterInterface
18
{
19
    /**
20
     * Mapping between the error handler component and JSON API error object
21
     * @see ErrorHandler::convertExceptionToArray()
22
     */
23
    const ERROR_EXCEPTION_MAPPING = [
24
        'title' => 'name',
25
        'detail' => 'message',
26
        'code' => 'code',
27
        'status' => 'status'
28
    ];
29
    /**
30
     * An error object MAY have the following members
31
     * @link http://jsonapi.org/format/#error-objects
32
     */
33
    const ERROR_ALLOWED_MEMBERS = [
34
        'id', 'links', 'status', 'code', 'title', 'detail', 'source', 'meta'
35
    ];
36
    /**
37
     * @var integer the encoding options passed to [[Json::encode()]]. For more details please refer to
38
     * <http://www.php.net/manual/en/function.json-encode.php>.
39
     * Default is `JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE`.
40
     */
41
    public $encodeOptions = 320;
42
    /**
43
     * @var bool whether to format the output in a readable "pretty" format. This can be useful for debugging purpose.
44
     * If this is true, `JSON_PRETTY_PRINT` will be added to [[encodeOptions]].
45
     * Defaults to `false`.
46
     */
47
    public $prettyPrint = false;
48
49
    /**
50
     * Formats response data in JSON format.
51
     * @link http://jsonapi.org/format/upcoming/#document-structure
52
     * @param Response $response
53
     */
54
    public function format($response)
55
    {
56
        $response->getHeaders()->set('Content-Type', 'application/vnd.api+json; charset=UTF-8');
57
        $options = $this->encodeOptions;
58
        if ($this->prettyPrint) {
59
            $options |= JSON_PRETTY_PRINT;
60
        }
61
62
        $apiDocument = $response->data;
63
64
        if (!$response->isEmpty) {
65
            $apiDocument = ['data' => $response->data];
66
            if (\Yii::$app->controller) {
67
                $apiDocument['links'] = Link::serialize([
68
                    Link::REL_SELF => Url::current([], true)
69
                ]);
70
            }
71
        }
72
73
        if ($response->isClientError || $response->isServerError) {
74
            if (ArrayHelper::isAssociative($response->data)) {
75
                $response->data = [$response->data];
76
            }
77
            $formattedErrors = [];
78
            foreach ($response->data as $error) {
79
                $formattedError = array_intersect_key($error, array_flip(static::ERROR_ALLOWED_MEMBERS));
80
                foreach (static::ERROR_EXCEPTION_MAPPING as $member => $key) {
81
                    if (isset($error[$key])) {
82
                        $formattedError[$member] = (string) $error[$key];
83
                    }
84
                }
85
                if (!empty($formattedError)) {
86
                    $formattedErrors[] = $formattedError;
87
                }
88
            }
89
            $apiDocument = ['errors' => $formattedErrors];
90
        }
91
        if ($apiDocument !== null) {
92
            $response->content = Json::encode($apiDocument, $options);
93
        }
94
    }
95
}
0 ignored issues
show
Coding Style introduced by
As per coding style, files should not end with a newline character.

This check marks files that end in a newline character, i.e. an empy line.

Loading history...
96