|
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
|
|
|
public function __construct( |
|
19
|
|
|
private HeaderInterface $header, |
|
20
|
|
|
private ConditionalResponseInterface $condResponse, |
|
21
|
|
|
) { |
|
22
|
|
|
} |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* {@inheritDoc} |
|
26
|
|
|
*/ |
|
27
|
|
|
public function __invoke(ResourceObject $ro, array $server): void |
|
28
|
|
|
{ |
|
29
|
|
|
/** @var array{HTTP_IF_NONE_MATCH?: string} $server */ |
|
30
|
|
|
$isModified = $this->condResponse->isModified($ro, $server); |
|
31
|
|
|
$output = $isModified ? $this->getOutput($ro, $server) : $this->condResponse->getOutput($ro->headers); |
|
|
|
|
|
|
32
|
|
|
|
|
33
|
|
|
$statusText = (new Code())->statusText[$ro->code] ?? ''; |
|
34
|
|
|
$ob = $output->code . ' ' . $statusText . PHP_EOL; |
|
35
|
|
|
|
|
36
|
|
|
// header |
|
37
|
|
|
foreach ($output->headers as $label => $value) { |
|
38
|
|
|
$ob .= "{$label}: {$value}" . PHP_EOL; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
// empty line |
|
42
|
|
|
$ob .= PHP_EOL; |
|
43
|
|
|
|
|
44
|
|
|
// body |
|
45
|
|
|
$ob .= (string) $output->view; |
|
46
|
|
|
|
|
47
|
|
|
echo $ob; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
/** @param array<string, string> $server */ |
|
51
|
|
|
private function getOutput(ResourceObject $ro, array $server): Output |
|
52
|
|
|
{ |
|
53
|
|
|
$ro->toString(); // set headers as well |
|
54
|
|
|
|
|
55
|
|
|
return new Output($ro->code, ($this->header)($ro, $server), (string) $ro->view ?: $ro->toString()); |
|
56
|
|
|
} |
|
57
|
|
|
} |
|
58
|
|
|
|