Completed
Pull Request — master (#1)
by Samuel
08:17
created

JsonApiResponse::send()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 9
ccs 0
cts 8
cp 0
rs 9.6666
c 0
b 0
f 0
cc 1
eloc 7
nc 1
nop 2
crap 2
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