CliResponder::__invoke()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 22

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 22
rs 9.568
c 0
b 0
f 0
cc 3
nc 4
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace BEAR\Package\Provide\Transfer;
6
7
use BEAR\Resource\Code;
8
use BEAR\Resource\ResourceObject;
9
use BEAR\Sunday\Extension\Transfer\TransferInterface;
10
use BEAR\Sunday\Provide\Transfer\ConditionalResponseInterface;
11
use BEAR\Sunday\Provide\Transfer\HeaderInterface;
12
use BEAR\Sunday\Provide\Transfer\Output;
13
14
use const PHP_EOL;
15
16
final class CliResponder implements TransferInterface
17
{
18
    /** @var HeaderInterface */
19
    private $header;
20
21
    /** @var ConditionalResponseInterface */
22
    private $condResponse;
23
24
    public function __construct(HeaderInterface $header, ConditionalResponseInterface $condResponse)
25
    {
26
        $this->header = $header;
27
        $this->condResponse = $condResponse;
28
    }
29
30
    /**
31
     * {@inheritdoc}
32
     */
33
    public function __invoke(ResourceObject $ro, array $server): void
34
    {
35
        /** @var array{HTTP_IF_NONE_MATCH?: string} $server */
36
        $isModified = $this->condResponse->isModified($ro, $server);
37
        $output = $isModified ? $this->getOutput($ro, $server) : $this->condResponse->getOutput($ro->headers);
38
39
        $statusText = (new Code())->statusText[$ro->code] ?? '';
40
        $ob = $output->code . ' ' . $statusText . PHP_EOL;
41
42
        // header
43
        foreach ($output->headers as $label => $value) {
44
            $ob .= "{$label}: {$value}" . PHP_EOL;
45
        }
46
47
        // empty line
48
        $ob .= PHP_EOL;
49
50
        // body
51
        $ob .= (string) $output->view;
52
53
        echo $ob;
54
    }
55
56
    /**
57
     * @param array<string, string> $server
58
     */
59
    private function getOutput(ResourceObject $ro, array $server): Output
60
    {
61
        $ro->toString(); // set headers as well
62
63
        return new Output($ro->code, ($this->header)($ro, $server), $ro->view ?: $ro->toString());
64
    }
65
}
66