Completed
Push — 1.x ( 0d0849...4327e3 )
by Akihito
13s
created

HttpResponder::isNotModified()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 3
nc 3
nop 2
dl 0
loc 5
ccs 4
cts 4
cp 1
crap 3
rs 10
c 0
b 0
f 0
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
     * {@inheritdoc}
14
     */
15 9
    public function __invoke(ResourceObject $ro, array $server)
16
    {
17 9
        if ($this->isNotModified($ro, $server)) {
18 1
            $this->transfer304($ro);
19
20 1
            return;
21
        }
22
23
        // render
24 8
        if (! $ro->view) {
25 8
            $ro->toString();
26
        }
27
28
        // header
29 8
        foreach ($ro->headers as $label => $value) {
30 8
            header("{$label}: {$value}", false);
31
        }
32
33
        // code
34 8
        http_response_code($ro->code);
35
36
        // body
37 8
        echo $ro->view;
38 8
    }
39
40 9
    private function isNotModified(ResourceObject $ro, array $server) : bool
41
    {
42 9
        return (isset($server['HTTP_IF_NONE_MATCH'])
43 9
            && isset($ro->headers['ETag'])
44 9
            && $server['HTTP_IF_NONE_MATCH'] === $ro->headers['ETag']
45
        );
46
    }
47
48
    /**
49
     * @see https://httpwg.org/specs/rfc7232.html#status.304
50
     */
51 1
    private function transfer304(ResourceObject $ro)
52
    {
53
        $mustGenerateHeaders = [
54 1
            'Cache-Control',
55
            'Content-Location',
56
            'Date',
57
            'ETag',
58
            'Expires',
59
            'Vary',
60
        ];
61
62
        // header
63 1
        foreach ($ro->headers as $label => $value) {
64 1
            if (! in_array($label, $mustGenerateHeaders, true)) {
65
                continue;
66
            }
67
68 1
            header("{$label}: {$value}", false);
69
        }
70
71
        // code
72 1
        http_response_code(304);
73 1
    }
74
}
75