-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResponseEmiter.php
More file actions
111 lines (98 loc) · 2.72 KB
/
ResponseEmiter.php
File metadata and controls
111 lines (98 loc) · 2.72 KB
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
<?php
/**
* Arikaim
*
* @link http://www.arikaim.com
* @copyright Copyright (c) Konstantin Atanasov <info@arikaim.com>
* @license http://www.arikaim.com/license
*
*/
namespace Arikaim\Core\Framework;
use Psr\Http\Message\ResponseInterface;
/**
* Error handler
*/
class ResponseEmiter
{
/**
* Emit headers
*
* @param ResponseInterface $response
* @return void
*/
public static function emitHeaders(ResponseInterface $response): void
{
foreach ($response->getHeaders() as $name => $values) {
$first = \strtolower($name) !== 'set-cookie';
foreach ($values as $value) {
header(\sprintf('%s: %s',$name,$value), $first);
$first = false;
}
}
// emit status line
\header(\sprintf(
'HTTP/%s %s %s',
$response->getProtocolVersion(),
$response->getStatusCode(),
$response->getReasonPhrase()
),true,$response->getStatusCode());
}
/**
* Emit response
*
* @param ResponseInterface $response
* @return void
*/
public static function emit(ResponseInterface $response): void
{
if (\headers_sent() === false) {
Self::emitHeaders($response);
}
$body = $response->getBody();
// emit body
$maxLength = 4096;
if ($body->isSeekable()) {
$body->rewind();
}
$read = (int)$response->getHeaderLine('Content-Length');
if ($read == false) {
$read = $body->getSize();
}
if ($read == true) {
while ($read > 0 && $body->eof() == false) {
$length = \min($maxLength,$read);
$data = $body->read($length);
echo $data;
$read -= strlen($data);
if (\connection_status() !== CONNECTION_NORMAL) {
break;
}
}
return;
}
while ($body->eof() == false) {
echo $body->read($maxLength);
if (\connection_status() !== CONNECTION_NORMAL) {
break;
}
}
}
/**
* Check if respose body is empty
*
* @param ResponseInterface $response
* @param object $body
* @return boolean
*/
public static function isEmpty(ResponseInterface $response, $body): bool
{
if (\in_array($response->getStatusCode(),[204,205,304],true)) {
return true;
}
if ($body->isSeekable() == true) {
$body->rewind();
return ($body->read(1) === '');
}
return $body->eof();
}
}