1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace pjpawel\LightApi\Http; |
4
|
|
|
|
5
|
|
|
use function function_exists; |
6
|
|
|
|
7
|
|
|
class Response |
8
|
|
|
{ |
9
|
|
|
|
10
|
|
|
public string $content; |
11
|
|
|
public ResponseStatus $status; |
12
|
|
|
public HeadersBag $headers; |
13
|
|
|
public string $version; |
14
|
|
|
|
15
|
|
|
public function __construct(string|array $content = '', ResponseStatus $status = ResponseStatus::OK, array $headers = [], $version = '1.0') |
16
|
|
|
{ |
17
|
|
|
$this->status = $status; |
18
|
|
|
$this->headers = new HeadersBag($headers); |
19
|
|
|
$this->version = $version; |
20
|
|
|
if (is_string($content)) { |
21
|
|
|
$this->content = $content; |
22
|
|
|
$this->headers->add('Content-Type', 'text/html'); |
23
|
|
|
} else { |
24
|
|
|
$this->content = json_encode($content); |
25
|
|
|
$this->headers->add('Content-Type', 'application/json'); |
26
|
|
|
} |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function send(): void |
30
|
|
|
{ |
31
|
|
|
$this->sendHeaders(); |
32
|
|
|
$this->sendContent(); |
33
|
|
|
|
34
|
|
|
if (function_exists('fastcgi_finish_request')) { |
35
|
|
|
fastcgi_finish_request(); |
36
|
|
|
} elseif (function_exists('litespeed_finish_request')) { |
37
|
|
|
litespeed_finish_request(); |
38
|
|
|
} /*elseif (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true)) { |
39
|
|
|
static::closeOutputBuffers(0, true); |
40
|
|
|
flush(); |
41
|
|
|
}*/ |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
private function sendHeaders(): void |
45
|
|
|
{ |
46
|
|
|
if (headers_sent()) { |
47
|
|
|
return; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
foreach ($this->headers->parameters as $key => $value) { |
51
|
|
|
header($key . ': ' . $value, true, $this->status->value); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/*foreach ($this->headers->allPreserveCaseWithoutCookies() as $name => $values) { |
55
|
|
|
//TODO: change |
56
|
|
|
$replace = 0 === strcasecmp($name, 'Content-Type'); |
57
|
|
|
foreach ($values as $value) { |
58
|
|
|
header($name.': '.$value, $replace, $this->status->value); |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
foreach ($this->headers->getCookies() as $cookie) { |
63
|
|
|
//TODO: |
64
|
|
|
header('Set-Cookie: '.$cookie, false, $this->status->value); |
65
|
|
|
}*/ |
66
|
|
|
|
67
|
|
|
// status |
68
|
|
|
header(sprintf('HTTP/%s %s %s', $this->version, $this->status->value, $this->status->getText()), true, $this->status->value); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
private function sendContent(): void |
72
|
|
|
{ |
73
|
|
|
echo $this->content; |
74
|
|
|
} |
75
|
|
|
} |