-
Notifications
You must be signed in to change notification settings - Fork 0
/
Request.php
527 lines (463 loc) · 15.6 KB
/
Request.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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
<?php
/*
* This file is part of the ICanBoogie package.
*
* (c) Olivier Laviale <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace ICanBoogie\HTTP;
use ICanBoogie\Accessor\AccessorTrait;
use ICanBoogie\HTTP\Headers\ContentType;
use InvalidArgumentException;
use function file_get_contents;
use function ICanBoogie\normalize_url_path;
use function json_decode;
use const JSON_THROW_ON_ERROR;
/**
* An HTTP request.
*
* ```php
* <?php
*
* use ICanBoogie\HTTP\Request;
*
* # Creating the main request
*
* $request = Request::from($_SERVER);
*
* # Creating a request from scratch, with the current environment.
*
* $request = Request::from([
*
* Request::OPTION_URI => '/path/to/my/page.html?page=2',
* Request::OPTION_USER_AGENT => 'Mozilla'
* Request::OPTION_IS_GET => true,
* Request::OPTION_IS_XHR => true,
* Request::OPTION_IS_LOCAL => true
*
* ], $_SERVER);
* ```
*
* @method Response connect(array $params = null)
* @method Response delete(array $params = null)
* @method Response get(array $params = null)
* @method Response head(array $params = null)
* @method Response options(array $params = null)
* @method Response post(array $params = null)
* @method Response put(array $params = null)
* @method Response patch(array $params = null)
* @method Response trace(array $params = null)
*
* @property-read Request\Context $context the request's context.
* @property-read Headers $headers the request's headers.
* @property-read FileList $files the request's files.
* @property-read bool $authorization Authorization of the request.
* @property-read int $content_length Length of the request content.
* @property-read string $ip Remote IP of the request.
* @property-read bool $is_local Is this a local request?
* @property-read bool $is_xhr Is this an Ajax request?
* @property-read RequestMethod $method Method of the request.
* @property-read string $normalized_path Path of the request normalized using the
* `\ICanBoogie\normalize_url_path` function.
* @property-read string $path Path info of the request.
* @property-read string $extension The extension of the path.
* @property-read int $port Port of the request.
* @property-read string $query_string Query string of the request.
* @property-read string $script_name Name of the entered script.
* @property-read string $referer Referer of the request.
* @property-read string $user_agent User agent of the request.
* @property-read string $uri URI of the request. The `QUERY_STRING` value of the environment
* is overwritten when the instance is created with the `$uri` property.
*
* @link https://en.wikipedia.org/wiki/Uniform_resource_locator
*/
final class Request implements RequestOptions
{
/**
* @uses get_context
* @uses get_headers
* @uses get_script_name
* @uses get_method
* @uses get_query_string
* @uses get_content_length
* @uses get_referer
* @uses get_user_agent
* @uses get_is_xhr
* @uses get_is_local
* @uses get_ip
* @uses get_authorization
* @uses get_uri
* @uses get_port
* @uses get_path
* @uses get_normalized_path
* @uses get_extension
*/
use AccessorTrait;
/**
* Parameters extracted from the request path.
*
* @var array<int|string, mixed>
*/
public array $path_params = [];
/**
* Parameters defined by the query string.
*
* @var array<string, mixed>
*/
public array $query_params = [];
/**
* Parameters defined by the request body.
*
* @var array<string, mixed>
*/
public mixed $request_params = [];
/**
* Union of {@see $path_params}, {@see $request_params} and {@see $query_params}.
*
* **Note**: The property is created during construct and is not updated after. If you modify one of
* {@see $path_params}, {@see $request_params} and {@see $query_params}, remember to modify {@see $params} as
* well.
*
* @var array<string, mixed>
*/
public array $params;
/**
* TODO: The property should be readonly but cloning is only available from PHP 8.3:
* https://www.php.net/releases/8.3/en.php#readonly_classes
*/
private Request\Context $context;
private function get_context(): Request\Context
{
return $this->context;
}
/**
* TODO: The property should be readonly but cloning is only available from PHP 8.3:
* https://www.php.net/releases/8.3/en.php#readonly_classes
*/
private Headers $headers;
private function get_headers(): Headers
{
return $this->headers;
}
/**
* Request environment.
*
* @var array<string, mixed>
*/
private array $env;
/**
* Files associated with the request.
*
* **Note**: The field is not readonly because it can be overwritten by `with()`.
*/
private FileList $files;
private function get_files(): FileList
{
return $this->files;
}
public $cookie;
/**
* A request may be created from the `$_SERVER` super global array. In that case `$_SERVER` is
* used as environment, the request is created with the following properties:
*
* - {@see $cookie}: a reference to the `$_COOKIE` super global.
* - {@see $path_params}: initialized to an empty array.
* - {@see $query_params}: a reference to the `$_GET` super global.
* - {@see $request_params}: a reference to the `$_POST` super global.
* - {@see $files}: a reference to the `$_FILES` super global.
*
* A request may also be created from an array of properties, in which case most of them are
* mapped to the `$env` constructor param. For instance, `is_xhr` set the
* `HTTP_X_REQUESTED_WITH` environment property to 'XMLHttpRequest'. In fact, only the
* following options are preserved:
*
* - Request::OPTION_PATH_PARAMS
* - Request::OPTION_QUERY_PARAMS
* - Request::OPTION_REQUEST_PARAMS
* - Request::OPTION_FILES: The files associated with the request.
* - Request::OPTION_HEADERS: The header fields of the request. If specified, the headers
* available in the environment are ignored.
*
* @phpstan-param array<RequestOptions::*, mixed>|string|null $properties Properties of the request.
*
* @param array<string, mixed> $env Environment, usually the `$_SERVER` array.
*
* @throws InvalidArgumentException in an attempt to use an unsupported option.
*/
public static function from(array|string|null $properties = null, array $env = []): self
{
if (!$properties) {
return new self([], $env);
}
if ($properties === $_SERVER) {
return self::from_server();
}
if (is_string($properties)) {
return self::from_uri($properties, $env);
}
return self::from_options($properties, $env);
}
/**
* Creates an instance from the `$_SERVER` array.
*/
private static function from_server(): self
{
$content_type = isset($_SERVER['HTTP_CONTENT_TYPE'])
? new ContentType($_SERVER['HTTP_CONTENT_TYPE'])
: null;
if ($content_type?->type === 'application/json') {
$json = file_get_contents('php://input');
$request_params = json_decode($json, true, flags: JSON_THROW_ON_ERROR);
} else {
$request_params = &$_POST;
}
return self::from([
self::OPTION_COOKIE => &$_COOKIE,
self::OPTION_PATH_PARAMS => [],
self::OPTION_QUERY_PARAMS => &$_GET,
self::OPTION_REQUEST_PARAMS => $request_params,
self::OPTION_FILES => &$_FILES, // @codeCoverageIgnore
], $_SERVER);
}
/**
* Creates an instance from a URI.
*
* @param array<string, mixed> $env
*/
private static function from_uri(string $uri, array $env): self
{
return self::from([ self::OPTION_URI => $uri ], $env);
}
/**
* Creates an instance from an array of properties.
*
* @param array<RequestOptions::*, mixed> $options
* @param array<string, mixed> $env
*
* @throws MethodNotAllowed
*/
private static function from_options(array $options, array $env): self
{
if ($options) {
$options = RequestOptionsMapper::map($options, $env);
}
if (!empty($env['QUERY_STRING'])) {
parse_str($env['QUERY_STRING'], $options[self::OPTION_QUERY_PARAMS]);
}
return new self($options, $env);
}
/**
* Initialize the properties {@see $env}, {@see $headers} and {@see $context}.
*
* If the {@see $params} property is `null` it is set with a union of {@see $path_params},
* {@see $request_params} and {@see $query_params}.
*
* @phpstan-param array<string, mixed> $options Initial properties.
*
* @param array<string, mixed> $env Environment of the request, usually the `$_SERVER` super global.
*
* @throws MethodNotAllowed when the request method is not supported.
*/
private function __construct(array $options, array $env = [])
{
$this->context = new Request\Context($this);
$this->env = $env;
$this->headers = $options[self::OPTION_HEADERS] ?? new Headers($env);
$this->files = $options[self::OPTION_FILES] ?? new FileList();
$this->path_params = $options[self::OPTION_PATH_PARAMS] ?? [];
$this->query_params = $options[self::OPTION_QUERY_PARAMS] ?? [];
$this->request_params = $options[self::OPTION_REQUEST_PARAMS] ?? [];
$this->params = $this->path_params + $this->request_params + $this->query_params;
$this->cookie = $options[self::OPTION_COOKIE] ?? null;
$this->assert_method($this->method);
}
/**
* Clone {@see $headers} and {@see $context}, and unset {@see $params}.
*/
public function __clone()
{
$this->headers = clone $this->headers;
$this->context = clone $this->context;
}
/**
* Asserts that a method is supported.
*/
private function assert_method(RequestMethod $method): void
{
}
/**
* Returns a new instance with the specified changed properties.
*
* @param array<RequestOptions::*, mixed> $options
*/
public function with(array $options): self
{
$changed = clone $this;
if ($options) {
$options = RequestOptionsMapper::map($options, $changed->env);
foreach ($options as $option => &$value) {
$changed->$option = $value;
}
}
$changed->params = $changed->path_params + $changed->request_params + $changed->query_params;
return $changed;
}
/**
* Returns the script name.
*
* The setter is volatile, the value is returned from the ENV key `SCRIPT_NAME`.
*/
private function get_script_name(): string
{
return $this->env['SCRIPT_NAME'];
}
/**
* Returns the request method.
*
* This is the getter for the `method` magic property.
*
* The method is retrieved from {@see $env}, if the key `REQUEST_METHOD` is not defined,
* the method defaults to {@see METHOD_GET}.
*/
private function get_method(): RequestMethod
{
$method = RequestMethod::from_mixed($this->env['REQUEST_METHOD'] ?? 'GET');
if ($method === RequestMethod::METHOD_POST && !empty($this->request_params['_method'])) {
$method = RequestMethod::from_mixed($this->request_params['_method']);
}
return $method;
}
/**
* Returns the query string of the request.
*
* The value is obtained from the `QUERY_STRING` key of the {@see $env} array.
*/
private function get_query_string(): ?string
{
return $this->env['QUERY_STRING'] ?? null;
}
/**
* Returns the content length of the request.
*
* The value is obtained from the `CONTENT_LENGTH` key of the {@see $env} array.
*/
private function get_content_length(): ?int
{
return $this->env['CONTENT_LENGTH'] ?? null;
}
/**
* Returns the referer of the request.
*
* The value is obtained from the `HTTP_REFERER` key of the {@see $env} array.
*/
private function get_referer(): ?string
{
return $this->env['HTTP_REFERER'] ?? null;
}
/**
* Returns the user agent of the request.
*
* The value is obtained from the `HTTP_USER_AGENT` key of the {@see $env} array.
*
* @return string|null
*/
private function get_user_agent(): ?string
{
return $this->env['HTTP_USER_AGENT'] ?? null;
}
/**
* Checks if the request is a `XMLHTTPRequest`.
*/
private function get_is_xhr(): bool
{
return !empty($this->env['HTTP_X_REQUESTED_WITH'])
&& str_contains($this->env['HTTP_X_REQUESTED_WITH'], 'XMLHttpRequest');
}
/**
* Checks if the request is local.
*/
private function get_is_local(): bool
{
$ip = $this->ip;
if ($ip == '::1' || preg_match('/^127\.0\.0\.\d{1,3}$/', $ip)) {
return true;
}
return preg_match('/^0:0:0:0:0:0:0:1(%.*)?$/', $ip);
}
/**
* Returns the remote IP of the request.
*
* If defined, the `HTTP_X_FORWARDED_FOR` header is used to retrieve the original IP.
*
* If the `REMOTE_ADDR` header is empty, the request is considered local; thus `::1` is returned.
*
* @link https://en.wikipedia.org/wiki/X-Forwarded-For
*/
private function get_ip(): string
{
$forwarded_for = $this->headers['X-Forwarded-For'];
if ($forwarded_for) {
[ $ip ] = explode(',', $forwarded_for);
return $ip;
}
return $this->env['REMOTE_ADDR'] ?? '::1';
}
private function get_authorization(): ?string
{
if (isset($this->env['HTTP_AUTHORIZATION'])) {
return $this->env['HTTP_AUTHORIZATION'];
} elseif (isset($this->env['X-HTTP_AUTHORIZATION'])) {
return $this->env['X-HTTP_AUTHORIZATION'];
} elseif (isset($this->env['X_HTTP_AUTHORIZATION'])) {
return $this->env['X_HTTP_AUTHORIZATION'];
} elseif (isset($this->env['REDIRECT_X_HTTP_AUTHORIZATION'])) {
return $this->env['REDIRECT_X_HTTP_AUTHORIZATION'];
}
return null;
}
/**
* Returns the `REQUEST_URI` environment key.
*
* If the `REQUEST_URI` key is not defined by the environment, the value is fetched from
* the `$_SERVER` array. If the key is not defined in the `$_SERVER` array `null` is returned.
*/
private function get_uri(): ?string
{
return $this->env['REQUEST_URI'] ?? ($_SERVER['REQUEST_URI'] ?? null);
}
/**
* Returns the port of the request.
*/
private function get_port(): int
{
return $this->env['REQUEST_PORT'];
}
/**
* Returns the path of the request, that is the `REQUEST_URI` without the query string.
*/
private function get_path(): string
{
$uri = $this->uri;
$qs_pos = strpos($uri, '?');
return ($qs_pos === false) ? $uri : substr($uri, 0, $qs_pos);
}
/**
* Returns the {@see $path} property normalized using the
* `ICanBoogie\normalize_url_path()` function.
*/
private function get_normalized_path(): string
{
return normalize_url_path($this->path);
}
/**
* Returns the extension of the path info.
*
* @return mixed
*/
private function get_extension()
{
return pathinfo($this->path, PATHINFO_EXTENSION);
}
}