-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpEmitter.php
More file actions
73 lines (65 loc) · 2.06 KB
/
Copy pathHttpEmitter.php
File metadata and controls
73 lines (65 loc) · 2.06 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
<?php
declare(strict_types=1);
namespace MaplePHP\Emitron\Emitters;
use MaplePHP\Emitron\Contracts\EmitterInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
class HttpEmitter implements EmitterInterface
{
/**
* Emits the final response to the client.
*
* Note: This method is expected to be the final step in the response lifecycle.
* Once called, headers and body are sent and can no longer be modified.
*
* @param ResponseInterface $response
* @param ServerRequestInterface $request
* @return void
*/
public function emit(ResponseInterface $response, ServerRequestInterface $request): void
{
$body = $response->getBody();
$status = $response->getStatusCode();
$method = strtoupper($request->getMethod());
$skipBody = in_array($status, [204, 304], true)
|| ($status >= 100 && $status < 200)
|| $method === 'HEAD';
if(!$response->hasHeader('Content-Type')) {
$response = $response->withHeader('Content-Type', 'text/html; charset=UTF-8');
}
// Create headers
$this->createHeaders($response);
// Detach body if HEAD or other detachable status code
if (!$skipBody) {
if ($body->isSeekable()) {
$body->rewind();
}
echo $body->getContents();
}
}
/**
* Check if a successful response
*
* @param ResponseInterface $response
* @return bool
*/
private function isSuccessfulResponse(ResponseInterface $response): bool
{
return $response->getStatusCode() === 200 || $response->getStatusCode() === 204;
}
/**
* Creates all prepared headers
*
* @param ResponseInterface $response
* @return void
*/
private function createHeaders(ResponseInterface $response): void
{
http_response_code($response->getStatusCode());
foreach ($response->getHeaders() as $name => $values) {
foreach ($values as $value) {
header("$name: $value", false);
}
}
}
}