-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathResponse.php
More file actions
234 lines (185 loc) · 6.99 KB
/
Copy pathResponse.php
File metadata and controls
234 lines (185 loc) · 6.99 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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
<?php
declare(strict_types=1);
namespace Zero\Lib\Http;
use JsonSerializable;
use RuntimeException;
use Throwable;
use Traversable;
use Zero\Lib\Http\Traits\BuildsResponse;
use Zero\Lib\Http\Traits\ManagesHeaders;
use Zero\Lib\Http\Traits\StreamsResponse;
use Zero\Lib\Router;
class Response
{
use BuildsResponse;
use ManagesHeaders;
use StreamsResponse;
protected int $status = 200;
protected string $content = '';
public static function make(mixed $content = '', int $status = 200, array $headers = []): static
{
return (new static())->setStatus($status)
->setContent((string) $content)
->withHeaders($headers)
->ensureContentType('text/html; charset=UTF-8');
}
public static function json(mixed $data, int $status = 200, array $headers = []): static
{
$payload = static::encodeJson($data);
return (new static())->setStatus($status)
->setContent($payload)
->withHeaders($headers)
->header('Content-Type', 'application/json; charset=UTF-8');
}
public static function text(string $text, int $status = 200, array $headers = []): static
{
return (new static())->setStatus($status)
->setContent($text)
->withHeaders($headers)
->ensureContentType('text/plain; charset=UTF-8');
}
public static function html(string $html, int $status = 200, array $headers = []): static
{
return (new static())->setStatus($status)
->setContent($html)
->withHeaders($headers)
->ensureContentType('text/html; charset=UTF-8');
}
public static function xml(string $xml, int $status = 200, array $headers = []): static
{
return (new static())->setStatus($status)
->setContent($xml)
->withHeaders($headers)
->header('Content-Type', 'application/xml; charset=UTF-8');
}
public static function api(string $status, mixed $payload = null, int $statusCode = 200, array $headers = []): static
{
$body = [
'code' => $statusCode,
'status' => $status,
'data' => $statusCode >= 400 ? null : $payload,
'error' => $statusCode >= 400 ? $payload : null,
];
return static::json($body, $statusCode, $headers);
}
public static function redirect(string $location, int $status = 302, array $headers = []): static
{
return static::make('', $status, $headers)->header('Location', $location);
}
public static function redirectRoute(string $name, array $parameters = [], bool $absolute = true, int $status = 302, array $headers = []): static
{
$url = Router::route($name, $parameters, $absolute);
return static::redirect($url, $status, $headers);
}
public static function redirectBack(string $fallback = '/', int $status = 302, array $headers = []): static
{
$referer = Request::instance()->header('referer', $fallback);
$target = $referer !== null && $referer !== '' ? $referer : $fallback;
return static::redirect($target, $status, $headers);
}
public static function stream(callable|string $stream, int $status = 200, array $headers = [], string $contentType = 'text/event-stream'): static
{
$response = new static();
$response->setStatus($status);
$response->stream($stream);
$response->withHeaders($headers);
$response->ensureContentType($contentType);
return $response;
}
public static function file(string $path, array $headers = [], ?string $name = null, string $disposition = 'inline'): static
{
if (!is_file($path)) {
throw new RuntimeException(sprintf('File [%s] does not exist.', $path));
}
$mime = mime_content_type($path) ?: 'application/octet-stream';
$size = filesize($path);
$name ??= basename($path);
$encodedName = addcslashes($name, '"\\');
$baseHeaders = [
'Content-Type' => $mime,
'Content-Disposition' => sprintf('%s; filename="%s"', $disposition, $encodedName),
];
if ($size !== false) {
$baseHeaders['Content-Length'] = (string) $size;
}
$merged = array_merge($baseHeaders, $headers);
$contents = file_get_contents($path);
if ($contents === false) {
throw new RuntimeException(sprintf('Unable to read file [%s].', $path));
}
return (new static())
->setStatus(200)
->withHeaders($merged)
->setContent($contents);
}
public static function noContent(int $status = 204, array $headers = []): static
{
return (new static())->setStatus($status)->withHeaders($headers)->setContent('');
}
public static function resolve(mixed $value): static
{
if ($value instanceof static) {
return $value;
}
if ($value instanceof self) {
return static::fromBase($value);
}
if ($value === null) {
return static::noContent();
}
if (is_array($value) || $value instanceof JsonSerializable || $value instanceof Traversable || is_object($value)) {
return static::json(static::normalizeIterable($value));
}
if ($value instanceof Throwable) {
return static::json([
'message' => $value->getMessage(),
'code' => $value->getCode(),
], 500);
}
if (is_bool($value)) {
return static::json($value);
}
return static::html((string) $value);
}
public function send(): void
{
http_response_code($this->status);
foreach ($this->getHeaders() as $name => $value) {
header($name . ': ' . $value, true);
}
$this->outputContent();
}
protected static function fromBase(self $response): static
{
$clone = new static();
$clone->setStatus($response->getStatus());
$clone->setContent($response->getContent());
$clone->withHeaders($response->getHeaders());
if ($response->streaming) {
$clone->streaming = true;
$clone->streamHandler = $response->streamHandler;
}
return $clone;
}
protected static function encodeJson(mixed $data): string
{
$encoded = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if ($encoded === false) {
throw new RuntimeException('Unable to encode data to JSON: ' . json_last_error_msg());
}
return $encoded;
}
protected static function normalizeIterable(mixed $value): mixed
{
if ($value instanceof JsonSerializable) {
return $value->jsonSerialize();
}
if ($value instanceof Traversable) {
return iterator_to_array($value);
}
if (is_object($value)) {
return get_object_vars($value);
}
return $value;
}
}