Passed
Push — 1.x ( be02b7...4dda68 )
by Akihito
02:56
created

HttpResponder::__invoke()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 21
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 3
nop 2
dl 0
loc 21
rs 10
c 0
b 0
f 0
ccs 10
cts 10
cp 1
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\Sunday\Provide\Transfer;
6
7
use BEAR\Resource\ResourceObject;
8
use BEAR\Sunday\Extension\Transfer\TransferInterface;
9
10
class HttpResponder implements TransferInterface
11
{
12
    /**
13
     * @var HeaderInterface
14
     */
15 9
    private $header;
16
17 9
    public function __construct(HeaderInterface $header)
18 1
    {
19
        $this->header = $header;
20 1
    }
21
22
    /**
23
     * {@inheritdoc}
24 8
     */
25 8
    public function __invoke(ResourceObject $ro, array $server)
26
    {
27
        if ($this->isNotModified($ro, $server)) {
28
            $this->transfer304($ro);
29 8
30 8
            return;
31
        }
32
33
        // render
34 8
        if (! $ro->view) {
35
            $ro->toString();
36
        }
37 8
38 8
        // header
39
        ($this->header)($ro, $server);
40 9
41
        // code
42 9
        http_response_code($ro->code);
43 9
44 9
        // body
45
        echo $ro->view;
46
    }
47
48
    private function isNotModified(ResourceObject $ro, array $server) : bool
49
    {
50
        return isset($server['HTTP_IF_NONE_MATCH'], $ro->headers['ETag']) && $server['HTTP_IF_NONE_MATCH'] === $ro->headers['ETag'];
51 1
    }
52
53
    /**
54 1
     * @see https://tools.ietf.org/html/rfc7232#section-4.1
55
     */
56
    private function transfer304(ResourceObject $ro)
57
    {
58
        $allowedHeaderIn304 = [
59
            'Cache-Control',
60
            'Content-Location',
61
            'Date',
62
            'ETag',
63 1
            'Expires',
64 1
            'Vary',
65
        ];
66
67
        // header
68 1
        foreach ($ro->headers as $label => $value) {
69
            if (! in_array($label, $allowedHeaderIn304, true)) {
70
                continue;
71
            }
72 1
73 1
            header("{$label}: {$value}", false);
74
        }
75
76
        // code
77
        http_response_code(304);
78
    }
79
}
80