|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Kelemen\ApiNette\Response; |
|
4
|
|
|
|
|
5
|
|
|
use Nette\Application\Responses\JsonResponse; |
|
6
|
|
|
use Nette\Http\IRequest; |
|
7
|
|
|
use Nette\Http\IResponse; |
|
8
|
|
|
use Nette\Utils\Json; |
|
9
|
|
|
use Nette\Utils\JsonException; |
|
10
|
|
|
|
|
11
|
|
|
class JsonApiResponse extends JsonResponse implements ApiResponse |
|
12
|
|
|
{ |
|
13
|
|
|
/** @var int */ |
|
14
|
|
|
private $code; |
|
15
|
|
|
|
|
16
|
|
|
/** @var string */ |
|
17
|
|
|
private $charset; |
|
18
|
|
|
|
|
19
|
|
|
/** @var string|null */ |
|
20
|
|
|
private $encodedData = null; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* @param int $code |
|
24
|
|
|
* @param array|\stdClass $data |
|
25
|
|
|
* @param string $contentType |
|
26
|
|
|
* @param string $charset |
|
27
|
|
|
*/ |
|
28
|
12 |
|
public function __construct($code, $data, $contentType = 'application/json', $charset = 'utf-8') |
|
29
|
|
|
{ |
|
30
|
12 |
|
parent::__construct($data, $contentType); |
|
31
|
12 |
|
$this->charset = $charset; |
|
32
|
12 |
|
$this->code = $code; |
|
33
|
12 |
|
} |
|
34
|
|
|
|
|
35
|
|
|
/** |
|
36
|
|
|
* Return api response http code |
|
37
|
|
|
* @return integer |
|
38
|
|
|
*/ |
|
39
|
12 |
|
public function getCode() |
|
40
|
|
|
{ |
|
41
|
12 |
|
return $this->code; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
/** |
|
45
|
|
|
* @return string |
|
46
|
|
|
* @throws JsonException |
|
47
|
|
|
*/ |
|
48
|
|
|
public function getEncodedData() |
|
49
|
|
|
{ |
|
50
|
|
|
if ($this->encodedData === null) { |
|
51
|
|
|
$this->encodedData = Json::encode($this->getPayload()); |
|
52
|
|
|
} |
|
53
|
|
|
return $this->encodedData; |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
/** |
|
57
|
|
|
* Return encoding charset for http response |
|
58
|
|
|
* @return string |
|
59
|
|
|
*/ |
|
60
|
12 |
|
public function getCharset() |
|
61
|
|
|
{ |
|
62
|
12 |
|
return $this->charset; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
/** |
|
66
|
|
|
* @param IRequest $httpRequest |
|
67
|
|
|
* @param IResponse $httpResponse |
|
68
|
|
|
*/ |
|
69
|
|
|
public function send(IRequest $httpRequest, IResponse $httpResponse) |
|
70
|
|
|
{ |
|
71
|
|
|
$httpResponse->setCode($this->getCode()); |
|
72
|
|
|
$httpResponse->setContentType($this->getContentType(), $this->charset); |
|
73
|
|
|
$httpResponse->setExpiration(false); |
|
74
|
|
|
$result = $this->getEncodedData(); |
|
75
|
|
|
$httpResponse->setHeader('Content-Length', strlen($result)); |
|
76
|
|
|
echo $result; |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
|