-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathResponse.php
executable file
·277 lines (249 loc) · 7.74 KB
/
Response.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
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
<?php
declare(strict_types=1);
namespace MaplePHP\Http;
use MaplePHP\Http\Interfaces\ResponseInterface;
use MaplePHP\Http\Interfaces\StreamInterface;
use MaplePHP\Http\Interfaces\HeadersInterface;
class Response extends Message implements ResponseInterface
{
public const PHRASE = [
100 => 'Continue',
101 => 'Switching Protocols',
102 => 'Processing',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
207 => 'Multi-Status',
226 => 'IM Used',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
306 => 'Reserved',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
418 => 'I\'m a teapot',
422 => 'Unprocessable Entity',
423 => 'Locked',
424 => 'Failed Dependency',
426 => 'Upgrade Required',
428 => 'Precondition Required',
429 => 'Too Many Requests',
431 => 'Request Header Fields Too Large',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
506 => 'Variant Also Negotiates',
507 => 'Insufficient Storage',
510 => 'Not Extended',
511 => 'Network Authentication Required',
];
private $statusCode = 200;
private $phrase;
private $description; // Can be used to describe status code
private $modDate;
private $hasHeadersInit;
public function __construct(
StreamInterface $body,
?HeadersInterface $headers = null,
int $status = 200,
?string $phrase = null,
?string $version = null
) {
$this->body = $body;
$this->statusCode = $status;
$this->headers = is_null($headers) ? new Headers() : $headers;
$this->body = $body;
if (!is_null($version)) {
$this->version = $version;
}
if (!is_null($phrase)) {
$this->phrase = $phrase;
}
}
/**
* Response with status code
* @param int $code
* @param string $reasonPhrase
* @return static
*/
public function withStatus(int $code, string $reasonPhrase = ''): ResponseInterface
{
$clone = clone $this;
$clone->statusCode = $code;
$clone->phrase = ($reasonPhrase ? $reasonPhrase : $clone->getReasonPhrase());
return $clone;
}
/**
* Get current response status code
* @return int
*/
public function getStatusCode()
{
return $this->statusCode;
}
/**
* Get current response status phrase
* @return string
*/
public function getReasonPhrase()
{
if (is_null($this->phrase)) {
$this->phrase = ($this::PHRASE[$this->statusCode] ?? "");
}
return $this->phrase;
}
/**
* Check is status response counts as a valid response
* HTTP response status codes in the 200 range generally indicate a successful or valid response.
* @return bool
*/
public function isValidResponse(): bool
{
return ($this->statusCode >= 200 && $this->statusCode < 300);
}
/**
* Get modified date
* @return int|null
*/
public function getModDate(): ?int
{
return $this->modDate;
}
/**
* Clear cache on modified date (E.g. can be used with uodate date on post in DB)
* @param string $date
* @return static
*/
public function withLastModified(string $date): ResponseInterface
{
$clone = clone $this;
$clone->modDate = strtotime($date);
return $clone->withHeader('Last-Modified', gmdate('D, d M Y H:i:s', $clone->modDate) . ' GMT');
}
/**
* Clear cache at given date (E.g. can be used if you set a publish date on a post in DB)
* @param string $date
* @return static
*/
public function withExpires(string $date): ResponseInterface
{
return $this->withHeader("Expires", gmdate('D, d M Y H:i:s', strtotime($date)) . ' GMT');
}
/**
* Set cache
* @param int $time expect timestamp
* @param int $ttl ttl in seconds
* @return static
*/
public function setCache(int $time, int $ttl): ResponseInterface
{
return $this->withHeaders([
"Cache-Control" => "max-age={$ttl}, immutable, public",
"Expires" => date("D, d M Y H:i:s", $time + $ttl) . " GMT",
"Pragma" => "public"
]);
}
/**
* Clear cache. No exceptions!
* Out of security reasons it is actually good practice to call this BY default on a framework
* The reason for this is to make sure that sensitive data is not cached.
* So then you as the developer can then make the choice to cache the data or not.
* @return static
*/
public function clearCache(): ResponseInterface
{
return $this->withHeaders([
"Cache-Control" => "no-store, no-cache, must-revalidate, private",
"Expires" => "Sat, 26 Jul 1997 05:00:00 GMT"
]);
}
/**
* Redirect to new location
* @param string $url URL
* @param int|integer $statusCode 301 or 302
* @return void
*/
public function location(string $url, int $statusCode = 302): void
{
if ($statusCode !== 301 && $statusCode !== 302) {
throw new \Exception("The second argument (statusCode) is expecting 301 or 302", 1);
}
$this->withStatus($statusCode)
->withHeader("Location", $url)
->createHeaders();
die();
}
/**
* Create headers createHeaders will only be executed once per instance
* @return void
*/
public function createHeaders(): void
{
if (is_null($this->hasHeadersInit)) {
$this->hasHeadersInit = true;
foreach ($this->getHeaders() as $key => $_unusedVal) {
$value = $this->getHeaderLine($key);
header("{$key}: {$value}");
}
}
}
/**
* Will build with the createHeaders method then and execute all the headers
* @return void
*/
public function executeHeaders(): void
{
$this->createHeaders();
$statusLine = sprintf(
'HTTP/%s %s %s',
$this->getProtocolVersion(),
$this->getStatusCode(),
$this->getReasonPhrase()
);
header($statusLine, true, $this->getStatusCode());
}
/**
* Set extra description, can be used to describe the error code more in details
* @param string $description
*/
public function setDescription(string $description): self
{
$this->description = $description;
return $this;
}
/**
* Get current response status description
* @return string|null
*/
public function getDescription(): ?string
{
return $this->description;
}
}