Passed
Push — master ( 12d735...10f25e )
by Paul
02:49
created

Response::checkContentType()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 2.1481

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 0
dl 0
loc 4
ccs 2
cts 3
cp 0.6667
crap 2.1481
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace CCT\Component\Rest\Http;
4
5
use CCT\Component\Rest\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 3
    public function __construct(string $content = '', int $status = 200, array $headers = array())
16
    {
17 3
        parent::__construct($content, $status, $headers);
18
19 3
        $this->data = $this->jsonToArray($content);
20 3
    }
21
22
    /**
23
     * {@inheritDoc}
24
     */
25 3
    public function getData()
26
    {
27 3
        return $this->data;
28
    }
29
30
    /**
31
     * {@inheritdoc}
32
     */
33 2
    public function setData($data)
34
    {
35 2
        $this->data = $data;
36 2
    }
37
38 3
    protected function jsonToArray(string $content = null): ?array
39
    {
40 3
        if (empty($content)) {
41
            return null;
42
        }
43
44 3
        $this->checkContentType();
45
46 3
        $data = @json_decode($content, true);
47 3
        if ($data === null && json_last_error() !== JSON_ERROR_NONE) {
48
            throw new \RuntimeException('It was not possible to convert the current content to JSON.');
49
        }
50
51 3
        return $data;
52
    }
53
54
    /**
55
     * Check if content type is json
56
     */
57 3
    protected function checkContentType()
58
    {
59 3
        if (false === strpos($this->headers->get('Content-Type'), 'json')) {
60
            throw new InvalidParameterException('The content returned must be in a JSON format.');
61
        }
62 3
    }
63
}
64