Completed
Push — master ( dfaf51...188ba1 )
by Samuel
02:15
created

JsonApiResponse::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
ccs 5
cts 5
cp 1
rs 9.4285
cc 1
eloc 4
nc 1
nop 4
crap 1
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
10
class JsonApiResponse extends JsonResponse
11
{
12
    /** @var int */
13
    private $code;
14
15
    /** @var string */
16
    private $charset;
17
18
    /**
19
     * @param int $code
20
     * @param array|\stdClass $data
21
     * @param string $contentType
22
     * @param string $charset
23
     */
24 4
    public function __construct($code, $data, $contentType = 'application/json', $charset = 'utf-8')
25
    {
26 4
        parent::__construct($data, $contentType);
27 4
        $this->charset = $charset;
28 4
        $this->code = $code;
29 4
    }
30
    /**
31
     * Return api response http code
32
     * @return integer
33
     */
34 4
    public function getCode()
35
    {
36 4
        return $this->code;
37
    }
38
    /**
39
     * Return encoding charset for http response
40
     * @return string
41
     */
42 2
    public function getCharset()
43
    {
44 2
        return $this->charset;
45
    }
46
47
    /**
48
     * @param IRequest $httpRequest
49
     * @param IResponse $httpResponse
50
     */
51
    public function send(IRequest $httpRequest, IResponse $httpResponse)
52
    {
53
        $httpResponse->setCode($this->getCode());
54
        $httpResponse->setContentType($this->getContentType(), $this->charset);
55
        $httpResponse->setExpiration(false);
56
        $result = Json::encode($this->getPayload());
57
        $httpResponse->setHeader('Content-Length', strlen($result));
58
        echo $result;
59
    }
60
}
61