-
Notifications
You must be signed in to change notification settings - Fork 0
/
HttpPublisher.php
117 lines (99 loc) · 2.93 KB
/
HttpPublisher.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php
/**
* Qubus\Http
*
* @link https://github.com/QubusPHP/http
* @copyright 2020
* @author Joshua Parker <joshua@joshuaparker.dev>
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
declare(strict_types=1);
namespace Qubus\Http;
use Exception;
use Laminas\HttpHandlerRunner\Emitter\EmitterInterface;
use LogicException;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
use Qubus\Http\Factories\HtmlResponseFactory;
use function flush;
use function function_exists;
use function header;
use function sprintf;
use function ucwords;
/**
* StreamPublisher publishes the given response.
*/
class HttpPublisher implements Publisher
{
/**
* {@inheritdoc}
*
* @throws LogicException|Exception
*/
public function publish(
ResponseInterface|StreamInterface $content,
?EmitterInterface $emitter
): bool|ResponseInterface {
$content = empty($content) ? '' : $content;
if (null !== $emitter && $content instanceof ResponseInterface) {
try {
return $emitter->emit($content);
} finally {
if (function_exists('fastcgi_finish_request')) {
fastcgi_finish_request();
}
}
}
if (null === $emitter && $content instanceof ResponseInterface) {
$this->emitResponseHeaders($content);
$content = $content->getBody();
}
flush();
if ($content instanceof StreamInterface) {
try {
return $this->emitStreamBody($content);
} finally {
if (function_exists('fastcgi_finish_request')) {
fastcgi_finish_request();
}
}
}
return HtmlResponseFactory::create(
'The response body must be an instance of ResponseInterface or StreamInterface',
200,
['Content-Type' => ['application/xhtml+xml']]
);
}
/**
* Emit the message body.
*/
private function emitStreamBody(StreamInterface $body): bool
{
if ($body->isSeekable()) {
$body->rewind();
}
if (! $body->isReadable()) {
echo $body;
return true;
}
while (! $body->eof()) {
echo $body->read(8192);
}
return true;
}
/**
* Emit the response header.
*/
private function emitResponseHeaders(ResponseInterface $response): void
{
$statusCode = $response->getStatusCode();
foreach ($response->getHeaders() as $name => $values) {
$name = ucwords($name, '-'); // Filter a header name to wordcase
$first = $name !== 'Set-Cookie';
foreach ($values as $value) {
header(sprintf('%s: %s', $name, $value), $first, $statusCode);
$first = false;
}
}
}
}