bearsunday /
BEAR.Package
| 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 | use Override; |
||
| 14 | |||
| 15 | use const PHP_EOL; |
||
| 16 | |||
| 17 | final class CliResponder implements TransferInterface |
||
| 18 | { |
||
| 19 | public function __construct( |
||
| 20 | private HeaderInterface $header, |
||
| 21 | private ConditionalResponseInterface $condResponse, |
||
| 22 | ) { |
||
| 23 | } |
||
| 24 | |||
| 25 | /** |
||
| 26 | * {@inheritDoc} |
||
| 27 | */ |
||
| 28 | #[Override] |
||
| 29 | public function __invoke(ResourceObject $ro, array $server): void |
||
| 30 | { |
||
| 31 | /** @var array{HTTP_IF_NONE_MATCH?: string} $server */ |
||
| 32 | $isModified = $this->condResponse->isModified($ro, $server); |
||
| 33 | $output = $isModified ? $this->getOutput($ro, $server) : $this->condResponse->getOutput($ro->headers); |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 34 | |||
| 35 | $statusText = (new Code())->statusText[$ro->code] ?? ''; |
||
| 36 | $ob = $output->code . ' ' . $statusText . PHP_EOL; |
||
| 37 | |||
| 38 | // header |
||
| 39 | foreach ($output->headers as $label => $value) { |
||
| 40 | $ob .= "{$label}: {$value}" . PHP_EOL; |
||
| 41 | } |
||
| 42 | |||
| 43 | // empty line |
||
| 44 | $ob .= PHP_EOL; |
||
| 45 | |||
| 46 | // body |
||
| 47 | $ob .= (string) $output->view; |
||
| 48 | |||
| 49 | echo $ob; |
||
| 50 | } |
||
| 51 | |||
| 52 | /** @param array<string, string> $server */ |
||
| 53 | private function getOutput(ResourceObject $ro, array $server): Output |
||
| 54 | { |
||
| 55 | $ro->toString(); // set headers as well |
||
| 56 | |||
| 57 | return new Output($ro->code, ($this->header)($ro, $server), (string) $ro->view ?: $ro->toString()); |
||
| 58 | } |
||
| 59 | } |
||
| 60 |