-
Notifications
You must be signed in to change notification settings - Fork 0
/
Request.php
622 lines (574 loc) · 17.5 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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
<?php
namespace Lead\Net\Http;
use UnexpectedValueException;
use Lead\Net\NetException;
use Lead\Text\Text;
use Lead\Set\Set;
use Lead\Net\Scheme;
use Lead\Net\Http\Cookie\CookieValues;
/**
* Facilitates HTTP request creation by assembling connection and path info, `GET` and `POST` data,
* and authentication credentials in a single, stateful object.
*/
class Request extends \Lead\Net\Http\Message implements \Psr\Http\Message\RequestInterface
{
use Psr7\MessageTrait, Psr7\RequestTrait;
/**
* The request's mode.
*
* @var string
*/
protected $_mode = null;
/**
* The method of the request, typically one of the following: `GET`, `POST`, `PUT`, `DELETE`,
* `OPTIONS`, `HEAD`, `TRACE` or `CONNECT`.
*
* @var string
*/
protected $_method = 'GET';
/**
* The communication protocol
*
* @var boolean
*/
protected $_scheme = 'http';
/**
* The port number, `null` for auto.
*
* @var integer
*/
protected $_port = null;
/**
* The hostname.
*
* @var string
*/
protected $_host = 'localhost';
/**
* The username.
*
* @var boolean
*/
protected $_username = null;
/**
* The password.
*
* @var string
*/
protected $_password = null;
/**
* Absolute path of the message.
*
* @var string
*/
protected $_path = '/';
/**
* Key/value pairs found encoded in the URL after the '?'.
*
* @var array
*/
protected $_query = [];
/**
* Fragement found in the URL after the '#'.
*
* @var array
*/
protected $_fragment = '';
/**
* Authentication type and parameters for HTTP Basic or Digest.
*
* Any array with a 'nonce' attribute implies Digest authentication; all other non-empty values
* for imply Basic authentication.
*
* @see lithium\net\http\Auth::encode()
* @var mixed
*/
protected $_auth = null;
/**
* Adds config values to the public properties when a new object is created.
*
* @param array $config Configuration options:
* - `'version'` _string_ : '1.1'
* - `'method'` _string_ : 'GET'
* - `'scheme'` _string_ : 'http'
* - `'host'` _string_ : 'localhost'
* - `'port'` _integer_: null
* - `'username'` _string_ : null
* - `'password'` _string_ : null
* - `'path'` _string_ : null
* - `'query'` _array_ : []
* - `'headers'` _array_ : []
* - `'mime'` _string_ : null
* - `'auth'` _mixed_ : null
* - `'body'` _mixed_ : null
*/
public function __construct($config = [])
{
$defaults = [
'scheme' => 'http',
'host' => 'localhost',
'port' => null,
'username' => null,
'password' => null,
'method' => 'GET',
'path' => '',
'query' => [],
'fragment' => '',
'auth' => null,
'mode' => 'origin'
];
$config = Set::merge($defaults, $config);
parent::__construct($config);
$headers = $this->headers();
if (!isset($headers['User-Agent'])) {
$headers->prepend('User-Agent', 'Mozilla/5.0');
}
if (!isset($headers['Connection'])) {
$headers->prepend('Connection', 'Close');
}
$this->mode($config['mode']);
$this->scheme($config['scheme']);
$this->port($config['port']);
$this->host($config['host']);
$this->username($config['username']);
$this->password($config['password']);
$this->method($config['method']);
$this->path($config['path']);
$this->query($config['query']);
$this->fragment($config['fragment']);
$this->auth($config['auth']);
}
/**
* Performs a format negotiation from a `Request` object, by iterating over the accepted
* content types in sequence, from most preferred to least.
*
* @param array $allowedFormats Some allowed formats.
*/
public function negotiate($allowedFormats = null)
{
$media = $this->_classes['media'];
$this->_format = $media::suitable($this, null, $allowedFormats);
}
/**
* Return information about the mime of content that the client is requesting.
*
* @return mixed Returns the the accepted content mimes sorted by client preference.
*/
public function accepts($accepts = [])
{
$headers = $this->headers();
if (func_num_args()) {
foreach ($accepts as $i => $value) {
if (is_string($value)) {
$q = 0;
} else {
$q = $value === 1 ? 0 : $value;
$value = $i;
}
$headers['Accept'][] = $value . ($q ? ';q=' . $q : '');
}
return $this;
}
$accepts = isset($headers['Accept']) ? $headers['Accept']->data() : ['text/html'];
$preferences = [];
foreach ($accepts as $i => $value) {
list($mime, $q) = preg_split('/;\s*q\s*=\s*/', $value, 2) + [$value, 1.0];
$stars = substr_count($mime, '*');
$score = $stars ? (0.03 - $stars * 0.01) : $q;
$score = $score * 100000 + strlen($mime); //RFC 4288 assumes a max length of 127/127 = 255 chars for mime.
$preferences[round($score)][strtolower(trim($mime))] = (float) $q;
}
krsort($preferences);
$preferences = call_user_func_array('array_merge', $preferences);
return $preferences;
}
/**
* Return information about the language that the client is requesting.
*
* @return mixed Returns the language sorted by client preference.
*/
public function locales($locales = [])
{
$headers = $this->headers();
if (func_num_args()) {
foreach ($locales as $i => $value) {
if (is_string($value)) {
$q = 0;
} else {
$q = $value === 1 ? 0 : $value;
$value = $i;
}
$headers['Accept-Language'][] = $value . ($q ? ';q=' . $q : '');
}
return $this;
}
$locales = isset($headers['Accept-Language']) ? $headers['Accept-Language']->data() : [];
$preferences = [];
foreach ($locales as $i => $value) {
list($mime, $q) = preg_split('/;\s*q\s*=\s*/', $value, 2) + [$value, 1.0];
$stars = substr_count($mime, '*');
$score = $stars ? (0.03 - $stars * 0.01) : $q;
$score = $score * 100000 + strlen($mime); //RFC 4288 assumes a max length of 127/127 = 255 chars for mime.
$preferences[$score][trim($mime)] = (float) $q;
}
krsort($preferences);
$preferences = call_user_func_array('array_merge', $preferences);
return $preferences;
}
/**
* Returns the prefered locale.
*
* @param boolean $full When true, return the full locale string like `'en'`, `'en_US'` or `'de_DE'`.
* @param string $default The default locale.
* @return string Returns the prefered locale.
*/
public function locale($full = false, $default = 'en')
{
$locales = $this->locales();
$locale = null;
foreach ($locales as $i => $value) {
$locale = is_string($value) ? $value : $i;
break;
}
$locale = $locale ?: $default;
return $full ? $locale : substr($locale, 0, 2);
}
/**
* Gets/sets the request's mode.
*
* @param string $mode The mode of the message
* @return string|self
*/
public function mode($mode = null)
{
if (func_num_args() === 0) {
return $this->_mode;
}
$this->_mode = $mode;
return $this;
}
/**
* Returns the status line.
*
* @return string
*/
public function line()
{
return $this->method() . ' ' . $this->requestTarget() . ' ' . $this->protocol();
}
/**
* Gets/sets the scheme.
*
* @param string $scheme The scheme of the message
* @return string|self
*/
public function scheme($scheme = null)
{
if (func_num_args() === 0) {
return $this->_scheme;
}
$this->_scheme = $scheme;
return $this;
}
/**
* Gets/sets the port.
*
* @param string $port The port of the message.
* @return string|self
*/
public function port($port = null)
{
if (func_num_args() === 1) {
$this->_port = $port;
return $this;
}
if ($this->_port !== null) {
return $this->_port;
}
$scheme = $this->_classes['scheme'];
$name = $this->scheme();
if ($scheme::registered($name)) {
return $scheme::port($name);
}
}
/**
* Gets/sets the path.
*
* @param string $path Absolute path of the message.
* @return string|self
*/
public function path($path = null)
{
if (!func_num_args()) {
return $this->_path;
}
$this->_path = '/' . ltrim($path, '/');
return $this;
}
/**
* Gets/sets the method.
*
* @param string $method The method name to set.
* @return mixed
*/
public function method($method = null)
{
if (func_num_args() === 0) {
return $this->_method;
}
$this->_method = strtoupper($method);
return $this;
}
/**
* Gets/sets the username.
*
* @param string $path The username of the message.
* @return string|self
*/
public function username($username = null)
{
if (func_num_args() === 0) {
return $this->_username;
}
$this->_username = $username ?: null;
return $this;
}
/**
* Gets/sets the password.
*
* @param string $path The password of the message.
* @return string|self
*/
public function password($password = null)
{
if (func_num_args() === 0) {
return $this->_password;
}
$this->_password = $password ?: null;
return $this;
}
/**
* Returns the message URI.
*
* @return string
*/
public function url()
{
$scheme = $this->scheme();
$scheme = $scheme ? $scheme . '://' : '//';
$query = $this->query() ? '?' . http_build_query($this->query()) : '';
$fragment = $this->fragment() ? '#' . $this->fragment() : '';
return $scheme . $this->host() . $this->path() . $query . $fragment;
}
/**
* Returns the credential.
*
* @return string|null The credential string.
*/
public function credential()
{
if (!$username = $this->username()) {
return '';
}
$credentials = $username;
if ($password = $this->password()) {
$credentials .= ':' . $password;
}
return $credentials;
}
/**
* Gets/sets the host.
*
* @param string $host The host of the message
* @return string|self
*/
public function host($host = null)
{
if (func_num_args() === 0) {
$scheme = $this->_classes['scheme'];
$port = $scheme::port($this->_scheme) !== $this->_port ? $this->_port : null;
return ($port !== null ? "{$this->_host}:{$port}" : $this->_host);
}
if (strpos($host, ':')) {
list($host, $port) = explode(':', $host);
$this->port($port);
}
$this->_host = $host;
$headers = $this->headers();
$headers->prepend('Host', $this->host());
return $this;
}
public function hostname()
{
return $this->_host;
}
/**
* Returns the request target present in the status line.
*
* @return string
*/
public function requestTarget()
{
if ($this->method() === 'CONNECT' || $this->mode() === 'authority') {
$credential = $this->credential();
return ($credential ? $credential. '@' : '') . $this->host();
}
if ($this->mode() === 'absolute') {
return $this->url();
}
if ($this->mode() === 'asterisk') {
return '*';
}
$query = $this->query() ? '?' . http_build_query($this->query()) : '';
$fragment = $this->fragment();
return $this->path() . $query . ($fragment ? '#' . $fragment : '');
}
/**
* Sets the request authorization.
*
* @param mixed $auth Any array with a 'nonce' attribute implies Digest authentication.
* Defaults to Basic authentication otherwise.
* If `false` the Authorization header will be removed.
* @return mixed
*/
public function auth($auth = true)
{
$headers = $this->headers();
if ($auth === false) {
unset($headers['Authorization']);
}
if (!$auth) {
return;
}
if (is_array($auth) && !empty($auth['nonce'])) {
$data = ['method' => $this->method(), 'uri' => $this->path()];
$data += $auth;
} else {
$data = [];
}
$auth = $this->_classes['auth'];
$data = $auth::encode($this->username(), $this->password(), $data);
$headers['Authorization'] = $auth::header($data);
return $this;
}
/**
* Gets/sets the query string.
*
* @param string|array $qs The query string to set or none to get the defined one.
* @return string
*/
public function query($qs = null)
{
if (func_num_args() === 0) {
return $this->_query;
}
if (is_string($qs)) {
parse_str($qs, $qs);
}
$this->_query = $qs + $this->_query;
return $this;
}
/**
* Gets/sets the fragment string.
*
* @param string $fragment The fragment string to set or none to get the defined one.
* @return string
*/
public function fragment($fragment = null)
{
if (func_num_args() === 0) {
return $this->_fragment;
}
$this->_fragment = $fragment;
return $this;
}
/**
* Auto adds a Content-Length header if necessary.
*
* @param object $request
*/
public function _setContentLength($noContent = false)
{
if (in_array($this->method(), ['GET', 'HEAD', 'DELETE'], true)) {
return;
}
parent::_setContentLength($noContent);
}
/**
* Set the Cookie header
*
* @param array $cookies The cookies.
* @return self
*/
public function applyCookies($cookies)
{
$values = [];
foreach ($cookies as $cookie) {
if ($cookie->matches($this->url())) {
$values[$cookie->path()] = $cookie->name() . '=' . $cookie->value();
}
}
$keys = array_map('strlen', array_keys($values));
array_multisort($keys, SORT_DESC, $values);
$headers = $this->headers();
if ($values) {
$headers['Cookie'] = implode('; ', $values);
} else {
unset($headers['Cookie']);
}
return $this;
}
/**
* Extract cookies value.
*
* @return array The cookies value.
*/
public function cookieValues()
{
$headers = $request->headers();
return isset($headers['Cookie']) ? CookieValues::toArray($headers['Cookie']->value()) : [];
}
/**
* Exports a `Request` instance to an array.
*
* @param mixed $request A `Request` instance.
* @param array $options Options.
* @return array The export array.
*/
public function export($options = [])
{
$this->_setContentLength();
return [
'method' => $this->method(),
'scheme' => $this->scheme(),
'version' => $this->version(),
'hostname' => $this->hostname(),
'port' => $this->port(),
'path' => $this->path(),
'query' => $this->query() ? '?' . http_build_query($this->query()) : '',
'fragment' => $this->fragment(),
'username' => $this->username(),
'password' => $this->password(),
'url' => $this->url()
];
}
/**
* Creates a request instance using an absolute URL.
*
* @param string $url An absolute URL.
* @param array $config The config array.
* @return self
*/
public static function create($method = 'GET', $url = null, $config = [])
{
if (func_num_args()) {
if(!preg_match('~^(?:[a-z]+:)?//~i', $url) || !$defaults = parse_url($url)) {
throw new NetException("Invalid url: `'{$url}'`.");
}
$defaults['username'] = isset($defaults['user']) ? $defaults['user'] : null;
$defaults['password'] = isset($defaults['pass']) ? $defaults['pass'] : null;
}
$config['method'] = strtoupper($method);
return new static($config + $defaults);
}
}