-
Notifications
You must be signed in to change notification settings - Fork 2
/
ServerRequest.php
1855 lines (1663 loc) · 55 KB
/
ServerRequest.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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 2.0.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\Http;
use BadMethodCallException;
use Cake\Core\Configure;
use Cake\Core\Exception\CakeException;
use Cake\Http\Cookie\CookieCollection;
use Cake\Http\Exception\MethodNotAllowedException;
use Cake\Utility\Hash;
use InvalidArgumentException;
use Laminas\Diactoros\PhpInputStream;
use Laminas\Diactoros\Stream;
use Laminas\Diactoros\UploadedFile;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\UploadedFileInterface;
use Psr\Http\Message\UriInterface;
use function Cake\Core\deprecationWarning;
use function Cake\Core\env;
/**
* A class that helps wrap Request information and particulars about a single request.
* Provides methods commonly used to introspect on the request headers and request body.
*/
class ServerRequest implements ServerRequestInterface
{
/**
* Array of parameters parsed from the URL.
*
* @var array
*/
protected $params = [
'plugin' => null,
'controller' => null,
'action' => null,
'_ext' => null,
'pass' => [],
];
/**
* Array of POST data. Will contain form data as well as uploaded files.
* In PUT/PATCH/DELETE requests this property will contain the form-urlencoded
* data.
*
* @var object|array|null
*/
protected $data = [];
/**
* Array of query string arguments
*
* @var array
*/
protected $query = [];
/**
* Array of cookie data.
*
* @var array<string, mixed>
*/
protected $cookies = [];
/**
* Array of environment data.
*
* @var array<string, mixed>
*/
protected $_environment = [];
/**
* Base URL path.
*
* @var string
*/
protected $base;
/**
* webroot path segment for the request.
*
* @var string
*/
protected $webroot = '/';
/**
* Whether to trust HTTP_X headers set by most load balancers.
* Only set to true if your application runs behind load balancers/proxies
* that you control.
*
* @var bool
*/
public $trustProxy = false;
/**
* Trusted proxies list
*
* @var array<string>
*/
protected $trustedProxies = [];
/**
* The built in detectors used with `is()` can be modified with `addDetector()`.
*
* There are several ways to specify a detector, see \Cake\Http\ServerRequest::addDetector() for the
* various formats and ways to define detectors.
*
* @var array<callable|array>
*/
protected static $_detectors = [
'get' => ['env' => 'REQUEST_METHOD', 'value' => 'GET'],
'post' => ['env' => 'REQUEST_METHOD', 'value' => 'POST'],
'put' => ['env' => 'REQUEST_METHOD', 'value' => 'PUT'],
'patch' => ['env' => 'REQUEST_METHOD', 'value' => 'PATCH'],
'delete' => ['env' => 'REQUEST_METHOD', 'value' => 'DELETE'],
'head' => ['env' => 'REQUEST_METHOD', 'value' => 'HEAD'],
'options' => ['env' => 'REQUEST_METHOD', 'value' => 'OPTIONS'],
'ssl' => ['env' => 'HTTPS', 'options' => [1, 'on']],
'https' => ['env' => 'HTTPS', 'options' => [1, 'on']],
'ajax' => ['env' => 'HTTP_X_REQUESTED_WITH', 'value' => 'XMLHttpRequest'],
'json' => ['accept' => ['application/json'], 'param' => '_ext', 'value' => 'json'],
'xml' => [
'accept' => ['application/xml', 'text/xml'],
'exclude' => ['text/html'],
'param' => '_ext',
'value' => 'xml',
],
];
/**
* Instance cache for results of is(something) calls
*
* @var array<string, bool>
*/
protected $_detectorCache = [];
/**
* Request body stream. Contains php://input unless `input` constructor option is used.
*
* @var \Psr\Http\Message\StreamInterface
*/
protected $stream;
/**
* Uri instance
*
* @var \Psr\Http\Message\UriInterface
*/
protected $uri;
/**
* Instance of a Session object relative to this request
*
* @var \Cake\Http\Session
*/
protected $session;
/**
* Instance of a FlashMessage object relative to this request
*
* @var \Cake\Http\FlashMessage
*/
protected $flash;
/**
* Store the additional attributes attached to the request.
*
* @var array<string, mixed>
*/
protected $attributes = [];
/**
* A list of properties that emulated by the PSR7 attribute methods.
*
* @var array<string>
*/
protected $emulatedAttributes = ['session', 'flash', 'webroot', 'base', 'params', 'here'];
/**
* Array of Psr\Http\Message\UploadedFileInterface objects.
*
* @var array
*/
protected $uploadedFiles = [];
/**
* The HTTP protocol version used.
*
* @var string|null
*/
protected $protocol;
/**
* The request target if overridden
*
* @var string|null
*/
protected $requestTarget;
/**
* Create a new request object.
*
* You can supply the data as either an array or as a string. If you use
* a string you can only supply the URL for the request. Using an array will
* let you provide the following keys:
*
* - `post` POST data or non query string data
* - `query` Additional data from the query string.
* - `files` Uploaded files in a normalized structure, with each leaf an instance of UploadedFileInterface.
* - `cookies` Cookies for this request.
* - `environment` $_SERVER and $_ENV data.
* - `url` The URL without the base path for the request.
* - `uri` The PSR7 UriInterface object. If null, one will be created from `url` or `environment`.
* - `base` The base URL for the request.
* - `webroot` The webroot directory for the request.
* - `input` The data that would come from php://input this is useful for simulating
* requests with put, patch or delete data.
* - `session` An instance of a Session object
*
* @param array<string, mixed> $config An array of request data to create a request with.
*/
public function __construct(array $config = [])
{
$config += [
'params' => $this->params,
'query' => [],
'post' => [],
'files' => [],
'cookies' => [],
'environment' => [],
'url' => '',
'uri' => null,
'base' => '',
'webroot' => '',
'input' => null,
];
$this->_setConfig($config);
}
/**
* Process the config/settings data into properties.
*
* @param array<string, mixed> $config The config data to use.
* @return void
*/
protected function _setConfig(array $config): void
{
if (empty($config['session'])) {
$config['session'] = new Session([
'cookiePath' => $config['base'],
]);
}
if (empty($config['environment']['REQUEST_METHOD'])) {
$config['environment']['REQUEST_METHOD'] = 'GET';
}
$this->cookies = $config['cookies'];
if (isset($config['uri'])) {
if (!$config['uri'] instanceof UriInterface) {
throw new CakeException('The `uri` key must be an instance of ' . UriInterface::class);
}
$uri = $config['uri'];
} else {
if ($config['url'] !== '') {
$config = $this->processUrlOption($config);
}
$uri = ServerRequestFactory::createUri($config['environment']);
}
$this->_environment = $config['environment'];
$this->uri = $uri;
$this->base = $config['base'];
$this->webroot = $config['webroot'];
if (isset($config['input'])) {
$stream = new Stream('php://memory', 'rw');
$stream->write($config['input']);
$stream->rewind();
} else {
$stream = new PhpInputStream();
}
$this->stream = $stream;
$this->data = $config['post'];
$this->uploadedFiles = $config['files'];
$this->query = $config['query'];
$this->params = $config['params'];
$this->session = $config['session'];
$this->flash = new FlashMessage($this->session);
}
/**
* Set environment vars based on `url` option to facilitate UriInterface instance generation.
*
* `query` option is also updated based on URL's querystring.
*
* @param array<string, mixed> $config Config array.
* @return array<string, mixed> Update config.
*/
protected function processUrlOption(array $config): array
{
if ($config['url'][0] !== '/') {
$config['url'] = '/' . $config['url'];
}
if (strpos($config['url'], '?') !== false) {
[$config['url'], $config['environment']['QUERY_STRING']] = explode('?', $config['url']);
parse_str($config['environment']['QUERY_STRING'], $queryArgs);
$config['query'] += $queryArgs;
}
$config['environment']['REQUEST_URI'] = $config['url'];
return $config;
}
/**
* Get the content type used in this request.
*
* @return string|null
*/
public function contentType(): ?string
{
$type = $this->getEnv('CONTENT_TYPE');
if ($type) {
return $type;
}
return $this->getEnv('HTTP_CONTENT_TYPE');
}
/**
* Returns the instance of the Session object for this request
*
* @return \Cake\Http\Session
*/
public function getSession(): Session
{
return $this->session;
}
/**
* Returns the instance of the FlashMessage object for this request
*
* @return \Cake\Http\FlashMessage
*/
public function getFlash(): FlashMessage
{
return $this->flash;
}
/**
* Get the IP the client is using, or says they are using.
*
* @return string The client IP.
*/
public function clientIp(): string
{
if ($this->trustProxy && $this->getEnv('HTTP_X_FORWARDED_FOR')) {
$addresses = array_map('trim', explode(',', (string)$this->getEnv('HTTP_X_FORWARDED_FOR')));
$trusted = (count($this->trustedProxies) > 0);
$n = count($addresses);
if ($trusted) {
$trusted = array_diff($addresses, $this->trustedProxies);
$trusted = (count($trusted) === 1);
}
if ($trusted) {
return $addresses[0];
}
return $addresses[$n - 1];
}
if ($this->trustProxy && $this->getEnv('HTTP_X_REAL_IP')) {
$ipaddr = $this->getEnv('HTTP_X_REAL_IP');
} elseif ($this->trustProxy && $this->getEnv('HTTP_CLIENT_IP')) {
$ipaddr = $this->getEnv('HTTP_CLIENT_IP');
} else {
$ipaddr = $this->getEnv('REMOTE_ADDR');
}
return trim((string)$ipaddr);
}
/**
* register trusted proxies
*
* @param array<string> $proxies ips list of trusted proxies
* @return void
*/
public function setTrustedProxies(array $proxies): void
{
$this->trustedProxies = $proxies;
$this->trustProxy = true;
$this->uri = $this->uri->withScheme($this->scheme());
}
/**
* Get trusted proxies
*
* @return array<string>
*/
public function getTrustedProxies(): array
{
return $this->trustedProxies;
}
/**
* Returns the referer that referred this request.
*
* @param bool $local Attempt to return a local address.
* Local addresses do not contain hostnames.
* @return string|null The referring address for this request or null.
*/
public function referer(bool $local = true): ?string
{
$ref = $this->getEnv('HTTP_REFERER');
$base = Configure::read('App.fullBaseUrl') . $this->webroot;
if (!empty($ref) && !empty($base)) {
if ($local && strpos($ref, $base) === 0) {
$ref = substr($ref, strlen($base));
if ($ref === '' || strpos($ref, '//') === 0) {
$ref = '/';
}
if ($ref[0] !== '/') {
$ref = '/' . $ref;
}
return $ref;
}
if (!$local) {
return $ref;
}
}
return null;
}
/**
* Missing method handler, handles wrapping older style isAjax() type methods
*
* @param string $name The method called
* @param array $params Array of parameters for the method call
* @return bool
* @throws \BadMethodCallException when an invalid method is called.
*/
public function __call(string $name, array $params)
{
if (strpos($name, 'is') === 0) {
$type = strtolower(substr($name, 2));
array_unshift($params, $type);
return $this->is(...$params);
}
throw new BadMethodCallException(sprintf('Method "%s()" does not exist', $name));
}
/**
* Check whether a Request is a certain type.
*
* Uses the built-in detection rules as well as additional rules
* defined with {@link \Cake\Http\ServerRequest::addDetector()}. Any detector can be called
* as `is($type)` or `is$Type()`.
*
* @param array<string>|string $type The type of request you want to check. If an array
* this method will return true if the request matches any type.
* @param mixed ...$args List of arguments
* @return bool Whether the request is the type you are checking.
* @throws \InvalidArgumentException If no detector has been set for the provided type.
*/
public function is($type, ...$args): bool
{
if (is_array($type)) {
foreach ($type as $_type) {
if ($this->is($_type)) {
return true;
}
}
return false;
}
$type = strtolower($type);
if (!isset(static::$_detectors[$type])) {
throw new InvalidArgumentException("No detector set for type `{$type}`");
}
if ($args) {
return $this->_is($type, $args);
}
return $this->_detectorCache[$type] = $this->_detectorCache[$type] ?? $this->_is($type, $args);
}
/**
* Clears the instance detector cache, used by the is() function
*
* @return void
*/
public function clearDetectorCache(): void
{
$this->_detectorCache = [];
}
/**
* Worker for the public is() function
*
* @param string $type The type of request you want to check.
* @param array $args Array of custom detector arguments.
* @return bool Whether the request is the type you are checking.
*/
protected function _is(string $type, array $args): bool
{
if ($type === 'ssl') {
deprecationWarning('The `ssl` detector is deprecated. Use `https` instead.');
}
$detect = static::$_detectors[$type];
if (is_callable($detect)) {
array_unshift($args, $this);
return $detect(...$args);
}
if (isset($detect['env']) && $this->_environmentDetector($detect)) {
return true;
}
if (isset($detect['header']) && $this->_headerDetector($detect)) {
return true;
}
if (isset($detect['accept']) && $this->_acceptHeaderDetector($detect)) {
return true;
}
if (isset($detect['param']) && $this->_paramDetector($detect)) {
return true;
}
return false;
}
/**
* Detects if a specific accept header is present.
*
* @param array $detect Detector options array.
* @return bool Whether the request is the type you are checking.
*/
protected function _acceptHeaderDetector(array $detect): bool
{
$content = new ContentTypeNegotiation();
$options = $detect['accept'];
// Some detectors overlap with the default browser Accept header
// For these types we use an exclude list to refine our content type
// detection.
$exclude = $detect['exclude'] ?? null;
if ($exclude) {
$options = array_merge($options, $exclude);
}
$accepted = $content->preferredType($this, $options);
if ($accepted === null) {
return false;
}
if ($exclude && in_array($accepted, $exclude, true)) {
return false;
}
return true;
}
/**
* Detects if a specific header is present.
*
* @param array $detect Detector options array.
* @return bool Whether the request is the type you are checking.
*/
protected function _headerDetector(array $detect): bool
{
foreach ($detect['header'] as $header => $value) {
$header = $this->getEnv('http_' . $header);
if ($header !== null) {
if (!is_string($value) && !is_bool($value) && is_callable($value)) {
return $value($header);
}
return $header === $value;
}
}
return false;
}
/**
* Detects if a specific request parameter is present.
*
* @param array $detect Detector options array.
* @return bool Whether the request is the type you are checking.
*/
protected function _paramDetector(array $detect): bool
{
$key = $detect['param'];
if (isset($detect['value'])) {
$value = $detect['value'];
return isset($this->params[$key]) ? $this->params[$key] == $value : false;
}
if (isset($detect['options'])) {
return isset($this->params[$key]) ? in_array($this->params[$key], $detect['options']) : false;
}
return false;
}
/**
* Detects if a specific environment variable is present.
*
* @param array $detect Detector options array.
* @return bool Whether the request is the type you are checking.
*/
protected function _environmentDetector(array $detect): bool
{
if (isset($detect['env'])) {
if (isset($detect['value'])) {
return $this->getEnv($detect['env']) == $detect['value'];
}
if (isset($detect['pattern'])) {
return (bool)preg_match($detect['pattern'], (string)$this->getEnv($detect['env']));
}
if (isset($detect['options'])) {
$pattern = '/' . implode('|', $detect['options']) . '/i';
return (bool)preg_match($pattern, (string)$this->getEnv($detect['env']));
}
}
return false;
}
/**
* Check that a request matches all the given types.
*
* Allows you to test multiple types and union the results.
* See Request::is() for how to add additional types and the
* built-in types.
*
* @param array<string> $types The types to check.
* @return bool Success.
* @see \Cake\Http\ServerRequest::is()
*/
public function isAll(array $types): bool
{
foreach ($types as $type) {
if (!$this->is($type)) {
return false;
}
}
return true;
}
/**
* Add a new detector to the list of detectors that a request can use.
* There are several different types of detectors that can be set.
*
* ### Callback comparison
*
* Callback detectors allow you to provide a callable to handle the check.
* The callback will receive the request object as its only parameter.
*
* ```
* addDetector('custom', function ($request) { //Return a boolean });
* ```
*
* ### Environment value comparison
*
* An environment value comparison, compares a value fetched from `env()` to a known value
* the environment value is equality checked against the provided value.
*
* ```
* addDetector('post', ['env' => 'REQUEST_METHOD', 'value' => 'POST']);
* ```
*
* ### Request parameter comparison
*
* Allows for custom detectors on the request parameters.
*
* ```
* addDetector('admin', ['param' => 'prefix', 'value' => 'admin']);
* ```
*
* ### Accept comparison
*
* Allows for detector to compare against Accept header value.
*
* ```
* addDetector('csv', ['accept' => 'text/csv']);
* ```
*
* ### Header comparison
*
* Allows for one or more headers to be compared.
*
* ```
* addDetector('fancy', ['header' => ['X-Fancy' => 1]);
* ```
*
* The `param`, `env` and comparison types allow the following
* value comparison options:
*
* ### Pattern value comparison
*
* Pattern value comparison allows you to compare a value fetched from `env()` to a regular expression.
*
* ```
* addDetector('iphone', ['env' => 'HTTP_USER_AGENT', 'pattern' => '/iPhone/i']);
* ```
*
* ### Option based comparison
*
* Option based comparisons use a list of options to create a regular expression. Subsequent calls
* to add an already defined options detector will merge the options.
*
* ```
* addDetector('mobile', ['env' => 'HTTP_USER_AGENT', 'options' => ['Fennec']]);
* ```
*
* You can also make compare against multiple values
* using the `options` key. This is useful when you want to check
* if a request value is in a list of options.
*
* `addDetector('extension', ['param' => '_ext', 'options' => ['pdf', 'csv']]`
*
* @param string $name The name of the detector.
* @param callable|array $detector A callable or options array for the detector definition.
* @return void
*/
public static function addDetector(string $name, $detector): void
{
$name = strtolower($name);
if (is_callable($detector)) {
static::$_detectors[$name] = $detector;
return;
}
if (isset(static::$_detectors[$name], $detector['options'])) {
/** @psalm-suppress PossiblyInvalidArgument */
$detector = Hash::merge(static::$_detectors[$name], $detector);
}
static::$_detectors[$name] = $detector;
}
/**
* Normalize a header name into the SERVER version.
*
* @param string $name The header name.
* @return string The normalized header name.
*/
protected function normalizeHeaderName(string $name): string
{
$name = str_replace('-', '_', strtoupper($name));
if (!in_array($name, ['CONTENT_LENGTH', 'CONTENT_TYPE'], true)) {
$name = 'HTTP_' . $name;
}
return $name;
}
/**
* Get all headers in the request.
*
* Returns an associative array where the header names are
* the keys and the values are a list of header values.
*
* While header names are not case-sensitive, getHeaders() will normalize
* the headers.
*
* @return array<string[]> An associative array of headers and their values.
* @link https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
*/
public function getHeaders(): array
{
$headers = [];
foreach ($this->_environment as $key => $value) {
$name = null;
if (strpos($key, 'HTTP_') === 0) {
$name = substr($key, 5);
}
if (strpos($key, 'CONTENT_') === 0) {
$name = $key;
}
if ($name !== null) {
$name = str_replace('_', ' ', strtolower($name));
$name = str_replace(' ', '-', ucwords($name));
$headers[$name] = (array)$value;
}
}
return $headers;
}
/**
* Check if a header is set in the request.
*
* @param string $name The header you want to get (case-insensitive)
* @return bool Whether the header is defined.
* @link https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
*/
public function hasHeader($name): bool
{
$name = $this->normalizeHeaderName($name);
return isset($this->_environment[$name]);
}
/**
* Get a single header from the request.
*
* Return the header value as an array. If the header
* is not present an empty array will be returned.
*
* @param string $name The header you want to get (case-insensitive)
* @return array<string> An associative array of headers and their values.
* If the header doesn't exist, an empty array will be returned.
* @link https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
*/
public function getHeader($name): array
{
$name = $this->normalizeHeaderName($name);
if (isset($this->_environment[$name])) {
return (array)$this->_environment[$name];
}
return [];
}
/**
* Get a single header as a string from the request.
*
* @param string $name The header you want to get (case-insensitive)
* @return string Header values collapsed into a comma separated string.
* @link https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
*/
public function getHeaderLine($name): string
{
$value = $this->getHeader($name);
return implode(', ', $value);
}
/**
* Get a modified request with the provided header.
*
* @param string $name The header name.
* @param array|string $value The header value
* @return static
* @link https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
*/
public function withHeader($name, $value)
{
$new = clone $this;
$name = $this->normalizeHeaderName($name);
$new->_environment[$name] = $value;
return $new;
}
/**
* Get a modified request with the provided header.
*
* Existing header values will be retained. The provided value
* will be appended into the existing values.
*
* @param string $name The header name.
* @param array|string $value The header value
* @return static
* @link https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
*/
public function withAddedHeader($name, $value)
{
$new = clone $this;
$name = $this->normalizeHeaderName($name);
$existing = [];
if (isset($new->_environment[$name])) {
$existing = (array)$new->_environment[$name];
}
$existing = array_merge($existing, (array)$value);
$new->_environment[$name] = $existing;
return $new;
}
/**
* Get a modified request without a provided header.
*
* @param string $name The header name to remove.
* @return static
* @link https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
*/
public function withoutHeader($name)
{
$new = clone $this;
$name = $this->normalizeHeaderName($name);
unset($new->_environment[$name]);
return $new;
}
/**
* Get the HTTP method used for this request.
* There are a few ways to specify a method.
*
* - If your client supports it you can use native HTTP methods.
* - You can set the HTTP-X-Method-Override header.
* - You can submit an input with the name `_method`
*
* Any of these 3 approaches can be used to set the HTTP method used
* by CakePHP internally, and will effect the result of this method.
*
* @return string The name of the HTTP method used.
* @link https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
*/
public function getMethod(): string
{
return (string)$this->getEnv('REQUEST_METHOD');
}
/**
* Update the request method and get a new instance.
*
* @param string $method The HTTP method to use.
* @return static A new instance with the updated method.
* @link https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
*/
public function withMethod($method)
{
$new = clone $this;
if (
!is_string($method) ||
!preg_match('/^[!#$%&\'*+.^_`\|~0-9a-z-]+$/i', $method)
) {
throw new InvalidArgumentException(sprintf(
'Unsupported HTTP method "%s" provided',
$method
));
}
$new->_environment['REQUEST_METHOD'] = $method;
return $new;
}
/**
* Get all the server environment parameters.
*
* Read all of the 'environment' or 'server' data that was
* used to create this request.
*
* @return array
* @link https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
*/
public function getServerParams(): array
{
return $this->_environment;
}
/**
* Get all the query parameters in accordance to the PSR-7 specifications. To read specific query values
* use the alternative getQuery() method.
*
* @return array
* @link https://www.php-fig.org/psr/psr-7/ This method is part of the PSR-7 server request interface.
*/
public function getQueryParams(): array
{
return $this->query;
}
/**
* Update the query string data and get a new instance.
*
* @param array $query The query string data to use