Formatter   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 11
c 1
b 0
f 0
dl 0
loc 41
rs 10
ccs 14
cts 14
cp 1
wmc 5

4 Methods

Rating   Name   Duplication   Size   Complexity  
A getOptions() 0 3 1
A init() 0 3 1
A format() 0 9 2
A setOptions() 0 3 1
1
<?php
2
namespace RazonYang\Yii2\JSend;
3
4
use RazonYang\JSend\PayloadInterface;
5
use yii\base\Component;
6
use yii\web\ResponseFormatterInterface;
7
8
/**
9
 * Formatter is a JSend formatter.
10
 *
11
 * @property int $options.
12
 */
13
class Formatter extends Component implements ResponseFormatterInterface
14
{
15
    /**
16
     * @var int $options JSON encode options.
17
     */
18
    private $options = JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES;
19
20
    /**
21
     * Returns JSON encode options.
22
     *
23
     * @return int
24
     */
25 3
    public function getOptions(): int
26
    {
27 3
        return $this->options;
28
    }
29
30
    /**
31
     * Sets JSON encode options.
32
     *
33
     * @param int $options
34
     */
35 1
    public function setOptions(int $options)
36
    {
37 1
        $this->options = $options;
38 1
    }
39
40 3
    public function init()
41
    {
42 3
        parent::init();
43 3
    }
44
45 2
    public function format($response)
46
    {
47 2
        if ($response->data instanceof PayloadInterface) {
48 1
            $data = $response->data->toArray();
49
        } else {
50 1
            $data = $response->data;
51
        }
52 2
        $response->getHeaders()->set('Content-Type', 'application/json; charset=UTF-8');
53 2
        $response->content = json_encode($data, $this->options);
54 2
    }
55
}
56