Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
100.00% |
13 / 13 |
|
100.00% |
1 / 1 |
CRAP | |
100.00% |
1 / 1 |
SendResponseHandler | |
100.00% |
13 / 13 |
|
100.00% |
1 / 1 |
7 | |
100.00% |
1 / 1 |
process | |
100.00% |
13 / 13 |
|
100.00% |
1 / 1 |
4 | |||
headersSent | n/a |
0 / 0 |
n/a |
0 / 0 |
1 | |||||
sendHeader | n/a |
0 / 0 |
n/a |
0 / 0 |
2 |
1 | <?php |
2 | |
3 | declare(strict_types=1); |
4 | |
5 | namespace Engelsystem\Middleware; |
6 | |
7 | use Psr\Http\Message\ResponseInterface; |
8 | use Psr\Http\Message\ServerRequestInterface; |
9 | use Psr\Http\Server\MiddlewareInterface; |
10 | use Psr\Http\Server\RequestHandlerInterface; |
11 | |
12 | class SendResponseHandler implements MiddlewareInterface |
13 | { |
14 | /** |
15 | * Send the server response to the client |
16 | * |
17 | * This should be the first middleware |
18 | */ |
19 | public function process( |
20 | ServerRequestInterface $request, |
21 | RequestHandlerInterface $handler |
22 | ): ResponseInterface { |
23 | $response = $handler->handle($request); |
24 | |
25 | if (!$this->headersSent()) { |
26 | $this->sendHeader(sprintf( |
27 | 'HTTP/%s %s %s', |
28 | $response->getProtocolVersion(), |
29 | $response->getStatusCode(), |
30 | $response->getReasonPhrase() |
31 | ), true, $response->getStatusCode()); |
32 | |
33 | foreach ($response->getHeaders() as $name => $values) { |
34 | foreach ($values as $value) { |
35 | $this->sendHeader($name . ': ' . $value, false); |
36 | } |
37 | } |
38 | } |
39 | |
40 | echo $response->getBody(); |
41 | return $response; |
42 | } |
43 | |
44 | /** |
45 | * Checks if headers have been sent |
46 | * |
47 | * @codeCoverageIgnore |
48 | */ |
49 | protected function headersSent(): bool |
50 | { |
51 | return headers_sent(); |
52 | } |
53 | |
54 | /** |
55 | * Send a raw HTTP header |
56 | * |
57 | * @codeCoverageIgnore |
58 | */ |
59 | protected function sendHeader(string $content, bool $replace = true, int $code = null): void |
60 | { |
61 | if (is_null($code)) { |
62 | header($content, $replace); |
63 | } else { |
64 | header($content, $replace, $code); |
65 | } |
66 | } |
67 | } |