Passed
Push — master ( 6f3eb0...8c456b )
by Anton
02:05
created

JsonApiResponseFormatter   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 5
dl 0
loc 40
rs 10
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B format() 0 19 6
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\web\Response;
12
use yii\web\ResponseFormatterInterface;
13
14
class JsonApiResponseFormatter extends Component implements ResponseFormatterInterface
15
{
16
    /**
17
     * @var integer the encoding options passed to [[Json::encode()]]. For more details please refer to
18
     * <http://www.php.net/manual/en/function.json-encode.php>.
19
     * Default is `JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE`.
20
     */
21
    public $encodeOptions = 320;
22
    /**
23
     * @var bool whether to format the output in a readable "pretty" format. This can be useful for debugging purpose.
24
     * If this is true, `JSON_PRETTY_PRINT` will be added to [[encodeOptions]].
25
     * Defaults to `false`.
26
     */
27
    public $prettyPrint = false;
28
29
    /**
30
     * Formats response data in JSON format.
31
     * @link http://jsonapi.org/format/upcoming/#document-structure
32
     * @param Response $response
33
     */
34
    public function format($response)
35
    {
36
        $response->getHeaders()->set('Content-Type', 'application/vnd.api+json; charset=UTF-8');
37
        if ($response->data !== null) {
38
            $options = $this->encodeOptions;
39
            if ($this->prettyPrint) {
40
                $options |= JSON_PRETTY_PRINT;
41
            }
42
            $apiDocument = $response->data;
43
            if ($response->isClientError || $response->isServerError) {
44
                if (ArrayHelper::isAssociative($response->data)) {
45
                    $response->data = [$response->data];
46
                }
47
                $apiDocument = ['errors' => $response->data];
48
            }
49
50
            $response->content = Json::encode($apiDocument, $options);
51
        }
52
    }
53
}
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...
54