|
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
|
|
|
/** |
|
16
|
|
|
* Response constructor. |
|
17
|
|
|
* |
|
18
|
|
|
* @param string $content |
|
19
|
|
|
* @param int $status |
|
20
|
|
|
* @param array $headers |
|
21
|
|
|
* |
|
22
|
|
|
* @throws \CCT\Component\Rest\Exception\InvalidParameterException |
|
23
|
|
|
* @throws \RuntimeException |
|
24
|
|
|
* @throws \InvalidArgumentException |
|
25
|
|
|
*/ |
|
26
|
22 |
|
public function __construct(string $content = '', int $status = 200, array $headers = array()) |
|
27
|
|
|
{ |
|
28
|
22 |
|
parent::__construct($content, $status, $headers); |
|
29
|
|
|
|
|
30
|
22 |
|
$this->data = $this->jsonToArray($content); |
|
31
|
20 |
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* {@inheritDoc} |
|
35
|
|
|
*/ |
|
36
|
19 |
|
public function getData() |
|
37
|
|
|
{ |
|
38
|
19 |
|
return $this->data; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* {@inheritdoc} |
|
43
|
|
|
*/ |
|
44
|
8 |
|
public function setData($data): void |
|
45
|
|
|
{ |
|
46
|
8 |
|
$this->data = $data; |
|
47
|
8 |
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* @param string|null $content |
|
51
|
|
|
* |
|
52
|
|
|
* @return array|null |
|
53
|
|
|
* @throws \CCT\Component\Rest\Exception\InvalidParameterException |
|
54
|
|
|
* @throws \RuntimeException |
|
55
|
|
|
*/ |
|
56
|
22 |
|
protected function jsonToArray(string $content = null): ?array |
|
57
|
|
|
{ |
|
58
|
22 |
|
if (empty($content)) { |
|
59
|
3 |
|
return null; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
19 |
|
$this->checkContentType(); |
|
63
|
|
|
|
|
64
|
17 |
|
$data = @json_decode($content, true); |
|
65
|
17 |
|
if ($data === null && json_last_error() !== JSON_ERROR_NONE) { |
|
66
|
|
|
throw new \RuntimeException('It was not possible to convert the current content to JSON.'); |
|
67
|
|
|
} |
|
68
|
|
|
|
|
69
|
17 |
|
return $data; |
|
70
|
|
|
} |
|
71
|
|
|
|
|
72
|
|
|
/** |
|
73
|
|
|
* Check if content type is json |
|
74
|
|
|
* |
|
75
|
|
|
* @throws \CCT\Component\Rest\Exception\InvalidParameterException |
|
76
|
|
|
*/ |
|
77
|
19 |
|
protected function checkContentType() |
|
78
|
|
|
{ |
|
79
|
19 |
|
if (false === strpos($this->headers->get('Content-Type'), 'json')) { |
|
80
|
2 |
|
throw new InvalidParameterException('The content returned must be in a JSON format.'); |
|
81
|
|
|
} |
|
82
|
17 |
|
} |
|
83
|
|
|
} |
|
84
|
|
|
|