Completed
Pull Request — master (#61)
by Tomas
03:17
created

JsonApiResponse   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

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

7 Methods

Rating   Name   Duplication   Size   Complexity  
A getCode() 0 4 1
A __construct() 0 8 2
A getPayload() 0 4 1
A getContentType() 0 4 1
A getCharset() 0 4 1
A getExpiration() 0 4 1
A send() 0 8 2
1
<?php
2
3
namespace Tomaj\NetteApi\Response;
4
5
use DateTimeInterface;
6
use Nette\Http\IRequest;
7
use Nette\Http\IResponse;
8
use Nette\SmartObject;
9
use Nette\Utils\Json;
10
11
class JsonApiResponse implements ResponseInterface
12
{
13
    use SmartObject;
14
15
    /** @var integer */
16
    private $code;
17
18
    /** @var array */
19
    private $payload;
20
21
    /** @var string */
22
    private $contentType;
23
24
    /** @var string */
25
    private $charset;
26
27
    /** @var DateTimeInterface|null */
28
    private $expiration;
29
30 21
    public function __construct(int $code, array $payload, string $contentType = 'application/json', string $charset = 'utf-8', ?DateTimeInterface $expiration = null)
31
    {
32 21
        $this->code = $code;
33 21
        $this->payload = $payload;
34 21
        $this->contentType = $contentType ?: 'application/json';
35 21
        $this->charset = $charset;
36 21
        $this->expiration = $expiration;
37 21
    }
38
39
    /**
40
     * {@inheritdoc}
41
     */
42 21
    public function getCode(): int
43
    {
44 21
        return $this->code;
45
    }
46
47 21
    public function getPayload(): array
48
    {
49 21
        return $this->payload;
50
    }
51
52 9
    public function getContentType(): string
53
    {
54 9
        return $this->contentType;
55
    }
56
57 9
    public function getCharset(): string
58
    {
59 9
        return $this->charset;
60
    }
61
62 3
    public function getExpiration(): ?DateTimeInterface
63
    {
64 3
        return $this->expiration;
65
    }
66
67
    /**
68
     * {@inheritdoc}
69
     */
70 3
    public function send(IRequest $httpRequest, IResponse $httpResponse): void
71
    {
72 3
        $httpResponse->setContentType($this->getContentType(), $this->getCharset());
73 3
        $httpResponse->setExpiration($this->getExpiration() ? $this->getExpiration()->format('c') : null);
74 3
        $result = Json::encode($this->getPayload());
75 3
        $httpResponse->setHeader('Content-Length', (string) strlen($result));
76 3
        echo $result;
77 3
    }
78
}
79