Completed
Push — master ( da99bb...533b8f )
by Samuel
10s
created

JsonApiResponse   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 40.91%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 3
dl 0
loc 68
ccs 9
cts 22
cp 0.4091
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A getCode() 0 4 1
A getEncodedData() 0 7 2
A getCharset() 0 4 1
A send() 0 9 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
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