Response::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 3
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace CCT\Kong\Http;
4
5
use CCT\Kong\Exception\InvalidParameterException;
6
use Symfony\Component\HttpFoundation\Response as BaseResponse;
7
8
class Response extends BaseResponse implements ResponseInterface
9
{
10
    /**
11
     * @var array
12
     */
13
    protected $data;
14
15 37
    public function __construct(string $content = '', int $status = 200, array $headers = array())
16
    {
17 37
        parent::__construct($content, $status, $headers);
18
19 37
        $this->data = $this->jsonToArray($content);
20 37
    }
21
22
    /**
23
     * {@inheritDoc}
24
     */
25 37
    public function getData()
26
    {
27 37
        return $this->data;
28
    }
29
30
    /**
31
     * {@inheritdoc}
32
     */
33 24
    public function setData($data)
34
    {
35 24
        $this->data = $data;
36 24
    }
37
38 37
    protected function jsonToArray(string $content = null): ?array
39
    {
40 37
        if (empty($content)) {
41
            return null;
42
        }
43
44 37
        if (false === strpos($this->headers->get('Content-Type'), 'json')) {
45
            throw new InvalidParameterException('The content returned must be in a JSON format.');
46
        }
47
48 37
        $data = @json_decode($content, true);
49 37
        if ($data === null && json_last_error() !== JSON_ERROR_NONE) {
50
            throw new \RuntimeException('It was not possible to convert the current content to JSON.');
51
        }
52
53 37
        return $data;
54
    }
55
}
56