• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

aplus-framework / http / 43501886023

13 Nov 2026 08:26PM UTC coverage: 99.021% (+0.007%) from 99.014%
43501886023

push

github

natanfelles
Add Request::{get,set}Host methods

12 of 12 new or added lines in 1 file covered. (100.0%)

4 existing lines in 1 file now uncovered.

1720 of 1737 relevant lines covered (99.02%)

15.73 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

98.43
/src/Request.php
1
<?php declare(strict_types=1);
2
/*
3
 * This file is part of Aplus Framework HTTP Library.
4
 *
5
 * (c) Natan Felles <natanfelles@gmail.com>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
namespace Aplus\Http;
11

12
use Aplus\Helpers\ArraySimple;
13
use BadMethodCallException;
14
use Closure;
15
use InvalidArgumentException;
16
use LogicException;
17
use Override;
18
use RequestParseBodyException;
19
use stdClass;
20
use UnexpectedValueException;
21

22
/**
23
 * Class Request.
24
 *
25
 * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/Messages#http_requests
26
 *
27
 * @package http
28
 */
29
class Request extends Message implements RequestInterface
30
{
31
    use Traits\ContentNegotiation;
32
    use Traits\RequestAuth;
33
    use Traits\RequestIp;
34
    /**
35
     * @var array<string,UploadedFile|array<mixed>>|null
36
     */
37
    protected ?array $files = null;
38
    /**
39
     * @var array<int,array<mixed>>|null
40
     */
41
    protected ?array $parsedBody = null;
42
    /**
43
     * @var array<string,mixed>|null
44
     */
45
    protected ?array $parseBodyOptions = null;
46
    protected Url | false | null $referrer = null;
47
    protected UserAgent | false | null $userAgent = null;
48
    protected bool $isAjax;
49
    /**
50
     * Tell if is an HTTPS connection.
51
     *
52
     * @var bool|null
53
     */
54
    protected ?bool $isSecure;
55
    /**
56
     * @var array<string>
57
     */
58
    protected array $allowedHosts = [];
59
    protected string $host;
60

61
    /**
62
     * Request constructor.
63
     *
64
     * @param array{
65
     *      host_key?: string|null,
66
     *      allowed_hosts?: array<string>,
67
     *      ip_key?: Closure|string,
68
     * } $config
69
     *
70
     * @throws UnexpectedValueException if invalid Host
71
     * @throws InvalidArgumentException for Host or IP key not set in the $_SERVER var
72
     */
73
    public function __construct(array $config = [])
74
    {
75
        $hostKey = $config['host_key'] ?? 'HTTP_HOST';
187 ✔
76
        $this->setHost($hostKey);
187 ✔
77
        if (isset($config['allowed_hosts'])) {
187 ✔
78
            $this->setAllowedHosts($config['allowed_hosts']);
11 ✔
79
        }
80
        if (isset($config['ip_key'])) {
187 ✔
81
            $this->setIpKey($config['ip_key']);
10 ✔
82
        }
83
        $this->setIp();
187 ✔
84
        $this->prepareStatusLine();
187 ✔
85
    }
86

87
    /**
88
     * @param string $method
89
     * @param array<int,mixed> $arguments
90
     *
91
     * @throws BadMethodCallException for method not allowed or method not found
92
     *
93
     * @return static
94
     */
95
    public function __call(string $method, array $arguments)
96
    {
97
        if ($method === 'setBody') {
7 ✔
98
            return $this->setBody(...$arguments);
5 ✔
99
        }
100
        if (\method_exists($this, $method)) {
2 ✔
101
            throw new BadMethodCallException("Method not allowed: {$method}");
1 ✔
102
        }
103
        throw new BadMethodCallException("Method not found: {$method}");
1 ✔
104
    }
105

106
    #[Override]
107
    public function toString() : string
108
    {
109
        if ($this->parseContentType() === 'multipart/form-data') {
2 ✔
110
            $this->setBody($this->getMultipartBody());
1 ✔
111
        }
112
        return parent::toString();
2 ✔
113
    }
114

115
    /**
116
     * NOTE: Created by comparing a request made with Firefox.
117
     *
118
     * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#multipartform-data
119
     *
120
     * @return string
121
     */
122
    protected function getMultipartBody() : string
123
    {
124
        $bodyParts = [];
1 ✔
125
        /**
126
         * @var array<string,string> $parsedBody
127
         */
128
        $parsedBody = ArraySimple::convert($this->getParsedBody());
1 ✔
129
        foreach ($parsedBody as $field => $value) {
1 ✔
130
            $field = \htmlspecialchars($field, \ENT_QUOTES | \ENT_HTML5);
1 ✔
131
            $bodyParts[] = \implode("\r\n", [
1 ✔
132
                "Content-Disposition: form-data; name=\"{$field}\"",
1 ✔
133
                '',
1 ✔
134
                $value,
1 ✔
135
            ]);
1 ✔
136
        }
137
        /**
138
         * @var array<string,UploadedFile> $files
139
         */
140
        $files = ArraySimple::convert($this->getFiles());
1 ✔
141
        foreach ($files as $field => $file) {
1 ✔
142
            $field = \htmlspecialchars($field, \ENT_QUOTES | \ENT_HTML5);
1 ✔
143
            $field = \preg_replace('/\[\d+]/', '[]', $field);
1 ✔
144
            $filename = \htmlspecialchars($file->getFullPath(), \ENT_QUOTES | \ENT_HTML5);
1 ✔
145
            $contentType = $file->getClientType() ?: 'application/octet-stream';
1 ✔
146
            $getContentsOf = $file->isMoved() ? $file->getDestination() : $file->getTmpName();
1 ✔
147
            $data = '';
1 ✔
148
            if ($getContentsOf !== '') {
1 ✔
149
                $data = \file_get_contents($getContentsOf);
1 ✔
150
            }
151
            $bodyParts[] = \implode("\r\n", [
1 ✔
152
                "Content-Disposition: form-data; name=\"{$field}\"; filename=\"{$filename}\"",
1 ✔
153
                'Content-Type: ' . $contentType,
1 ✔
154
                '',
1 ✔
155
                $data,
1 ✔
156
            ]);
1 ✔
157
        }
158
        $boundary = '';
1 ✔
159
        $boundaryParts = \explode(';', $this->getContentType());
1 ✔
160
        foreach ($boundaryParts as $boundaryPart) {
1 ✔
161
            $boundaryPart = \trim($boundaryPart);
1 ✔
162
            if (\str_starts_with(\strtolower($boundaryPart), 'boundary=')) {
1 ✔
163
                $boundary = \substr($boundaryPart, \strlen('boundary='));
1 ✔
164
                break;
1 ✔
165
            }
166
        }
167
        foreach ($bodyParts as &$part) {
1 ✔
168
            $part = "--{$boundary}\r\n{$part}";
1 ✔
169
        }
170
        unset($part);
1 ✔
171
        $bodyParts[] = "--{$boundary}--";
1 ✔
172
        $bodyParts[] = '';
1 ✔
173
        $bodyParts = \implode("\r\n", $bodyParts);
1 ✔
174
        /**
175
         * Uncomment the code below to make a raw test.
176
         *
177
         * @see \Tests\HTTP\RequestTest::testToStringMultipart()
178
         */
179
        /*
180
        $serverLength = (string) $_SERVER['CONTENT_LENGTH'];
181
        $algoLength = (string) \strlen($bodyParts);
182
        \var_dump($serverLength, $algoLength);
183
        if ($serverLength !== $algoLength) {
184
            throw new \Exception(
185
                '$_SERVER CONTENT_LENGTH is ' . $serverLength
186
                . ', but the algorithm calculated ' . $algoLength
187
            );
188
        }
189
        */
190
        return $bodyParts;
1 ✔
191
    }
192

193
    protected function setHost(string $key) : static
194
    {
195
        if (!isset($_SERVER[$key])) {
187 ✔
196
            throw new InvalidArgumentException(
1 ✔
197
                'The Host Key "' . $key . '" is not set in the $_SERVER'
1 ✔
198
            );
1 ✔
199
        }
200
        $this->host = $_SERVER[$key];
187 ✔
201
        return $this;
187 ✔
202
    }
203

204
    public function getHost() : string
205
    {
206
        return $this->host;
187 ✔
207
    }
208

209
    /**
210
     * Check if Host header is allowed. And set allowed hosts.
211
     *
212
     * @see https://expressionengine.com/blog/http-host-and-server-name-security-issues
213
     * @see http://nginx.org/en/docs/http/request_processing.html
214
     *
215
     * @param array<string> $allowedHosts
216
     *
217
     * @return static
218
     */
219
    protected function setAllowedHosts(array $allowedHosts) : static
220
    {
221
        if (empty($allowedHosts)) {
11 ✔
222
            $this->allowedHosts = $allowedHosts;
1 ✔
223
            return $this;
1 ✔
224
        }
225
        if (!\in_array($this->getHost(), $allowedHosts, true)) {
10 ✔
226
            throw new UnexpectedValueException('Invalid Host: ' . $this->getHost());
1 ✔
227
        }
228
        $this->allowedHosts = $allowedHosts;
9 ✔
229
        return $this;
9 ✔
230
    }
231

232
    /**
233
     * Get the allowed hosts.
234
     *
235
     * @return array<string>
236
     */
237
    public function getAllowedHosts() : array
238
    {
239
        return $this->allowedHosts;
15 ✔
240
    }
241

242
    protected function prepareStatusLine() : void
243
    {
244
        $this->setProtocol($_SERVER['SERVER_PROTOCOL']);
187 ✔
245
        $this->setMethod($_SERVER['REQUEST_METHOD']);
187 ✔
246
        $url = $this->isSecure() ? 'https' : 'http';
187 ✔
247
        $url .= '://' . $this->getHost();
187 ✔
248
        $url .= $_SERVER['REQUEST_URI'];
187 ✔
249
        $this->setUrl($url);
187 ✔
250
    }
251

252
    public function getHeader(string $name) : ?string
253
    {
254
        $this->prepareHeaders();
44 ✔
255
        return $this->headers[\strtolower($name)] ?? null;
44 ✔
256
    }
257

258
    /**
259
     * @return array<string,string>
260
     */
261
    public function getHeaders() : array
262
    {
263
        $this->prepareHeaders();
16 ✔
264
        return $this->headers;
16 ✔
265
    }
266

267
    protected function prepareHeaders() : void
268
    {
269
        if (!empty($this->headers)) {
46 ✔
270
            return;
36 ✔
271
        }
272
        foreach ($_SERVER as $name => $value) {
29 ✔
273
            if (\str_starts_with($name, 'HTTP_')) {
29 ✔
274
                $name = \strtr(\substr($name, 5), ['_' => '-']);
29 ✔
275
                $this->setHeader($name, (string) $value);
29 ✔
276
            }
277
        }
278
        if (isset($_SERVER['CONTENT_TYPE'])) {
29 ✔
279
            $this->setHeader('Content-Type', (string) $_SERVER['CONTENT_TYPE']);
15 ✔
280
        }
281
        if (isset($_SERVER['CONTENT_LENGTH'])) {
29 ✔
282
            $this->setHeader('Content-Length', (string) $_SERVER['CONTENT_LENGTH']);
15 ✔
283
        }
284
    }
285

286
    public function getCookie(string $name) : ?Cookie
287
    {
288
        $this->prepareCookies();
1 ✔
289
        return $this->cookies[$name] ?? null;
1 ✔
290
    }
291

292
    /**
293
     * Get all Cookies.
294
     *
295
     * @return array<string,Cookie>
296
     */
297
    public function getCookies() : array
298
    {
299
        $this->prepareCookies();
1 ✔
300
        return $this->cookies;
1 ✔
301
    }
302

303
    protected function prepareCookies() : void
304
    {
305
        if (!empty($this->cookies)) {
2 ✔
306
            return;
1 ✔
307
        }
308
        foreach ($_COOKIE as $name => $value) {
2 ✔
309
            $this->setCookie(new Cookie($name, $value));
2 ✔
310
        }
311
    }
312

313
    /**
314
     * @see https://www.php.net/manual/en/wrappers.php.php#wrappers.php.input
315
     *
316
     * @return string
317
     */
318
    public function getBody() : string
319
    {
320
        if (!isset($this->body)) {
22 ✔
321
            $this->body = (string) \file_get_contents('php://input');
17 ✔
322
        }
323
        return $this->body;
22 ✔
324
    }
325

326
    protected function prepareFiles() : void
327
    {
328
        if (isset($this->files)) {
17 ✔
329
            return;
14 ✔
330
        }
331
        $this->files = $this->getInputFiles();
17 ✔
332
    }
333

334
    /**
335
     * @param int $type
336
     * @param string|null $name
337
     * @param int|null $filter
338
     * @param array<int,int>|int $options
339
     *
340
     * @see https://www.php.net/manual/en/function.filter-var
341
     * @see https://www.php.net/manual/en/filter.filters.php
342
     *
343
     * @return mixed
344
     */
345
    protected function filterInput(
346
        int $type,
347
        ?string $name = null,
348
        ?int $filter = null,
349
        array | int $options = 0
350
    ) : mixed {
351
        $input = match ($type) {
26 ✔
352
            \INPUT_POST => $_POST,
10 ✔
353
            \INPUT_GET => $_GET,
1 ✔
354
            \INPUT_COOKIE => $_COOKIE,
1 ✔
355
            \INPUT_ENV => $_ENV,
1 ✔
356
            \INPUT_SERVER => $_SERVER,
14 ✔
357
            default => throw new InvalidArgumentException('Invalid input type: ' . $type)
1 ✔
358
        };
26 ✔
359
        if ($name !== null) {
25 ✔
360
            $input = \in_array($type, [\INPUT_POST, \INPUT_GET], true)
22 ✔
361
                ? ArraySimple::value($name, $input)
7 ✔
362
                : $input[$name] ?? null;
15 ✔
363
        }
364
        if ($filter !== null) {
25 ✔
365
            $input = \filter_var($input, $filter, $options);
2 ✔
366
        }
367
        return $input;
25 ✔
368
    }
369

370
    /**
371
     * Force an HTTPS connection on same URL.
372
     */
373
    public function forceHttps() : void
374
    {
375
        if (!$this->isSecure()) {
2 ✔
376
            \header(
1 ✔
377
                'Location: ' . $this->getUrl()->setScheme('https'),
1 ✔
378
                true,
1 ✔
379
                Status::MOVED_PERMANENTLY
1 ✔
380
            );
1 ✔
381
            if (!\defined('TESTING')) {
1 ✔
382
                // @codeCoverageIgnoreStart
383
                exit;
384
                // @codeCoverageIgnoreEnd
385
            }
386
        }
387
    }
388

389
    /**
390
     * Parses and filters the request body.
391
     *
392
     * Get data when the request the Content-Type is
393
     * `application/x-www-form-urlencoded` or `multipart/form-data`.
394
     *
395
     * Files can be obtained using the {@see Framework\HTTP\Request::getFiles()}
396
     * method.
397
     *
398
     * @param string|null $name The array key name as a string, or null to return all data
399
     * @param int|null $filter Optional filter applied to the value returned with `$name`
400
     * @param array<int,int>|int $filterOptions Filter options
401
     *
402
     * @throws RequestParseBodyException for errors when parsing the body
403
     *
404
     * @return mixed Returns the value according to the `$name` and the filtering
405
     */
406
    public function getParsedBody(
407
        ?string $name = null,
408
        ?int $filter = null,
409
        array | int $filterOptions = 0
410
    ) : mixed {
411
        if ($this->isMethod(Method::POST)) {
9 ✔
412
            return $this->getPost($name, $filter, $filterOptions);
9 ✔
413
        }
414
        return $this->getFilteredParsedBody($name, $filter, $filterOptions);
1 ✔
415
    }
416

417
    /**
418
     * Parses and filters the request body.
419
     *
420
     * Get data when the request the Content-Type is
421
     * `application/x-www-form-urlencoded` or `multipart/form-data`.
422
     *
423
     * Files can be obtained using the {@see Framework\HTTP\Request::getFiles()}
424
     * method.
425
     *
426
     * @param string|null $name The array key name as a string, or null to return all data
427
     * @param int|null $filter Optional filter applied to the value returned with `$name`
428
     * @param array<int,int>|int $filterOptions Filter options
429
     *
430
     * @throws RequestParseBodyException for errors when parsing the body
431
     *
432
     * @return mixed Returns the value according to the `$name` and the filtering
433
     */
434
    protected function getFilteredParsedBody(
435
        ?string $name = null,
436
        ?int $filter = null,
437
        array | int $filterOptions = 0
438
    ) : mixed {
439
        if (!$this->isParsedBody()) {
3 ✔
440
            $this->parseBody($this->getParseBodyOptions());
3 ✔
441
        }
442
        $variable = $name === null
3 ✔
443
            ? $this->parsedBody[0]
3 ✔
444
            : ArraySimple::value($name, $this->parsedBody[0]);
3 ✔
445
        return $filter === null
3 ✔
446
            ? $variable
3 ✔
447
            : \filter_var($variable, $filter, $filterOptions);
3 ✔
448
    }
449

450
    /**
451
     * Parses the request body.
452
     *
453
     * @param array{
454
     *      max_file_uploads?: int|string,
455
     *      max_input_vars?: int|string,
456
     *      max_multipart_body_parts?: int|string,
457
     *      post_max_size?: int|string,
458
     *      upload_max_filesize?: int|string,
459
     * }|null $options Options used in {@see request_parse_body()}
460
     *
461
     * @throws RequestParseBodyException for errors when parsing the body
462
     * @throws LogicException when the body has already been parsed
463
     *
464
     * @return static
465
     */
466
    public function parseBody(?array $options = null) : static
467
    {
468
        if ($this->isParsedBody()) {
5 ✔
469
            throw new LogicException('Parse error: the request body has already been parsed');
1 ✔
470
        }
471
        $options ??= $this->getParseBodyOptions();
5 ✔
472
        $this->parsedBody = $this->requestParseBody($options);
5 ✔
473
        return $this;
5 ✔
474
    }
475

476
    /**
477
     * Call the request_parse_body() function.
478
     *
479
     * @param array{
480
     *      max_file_uploads?: int|string,
481
     *      max_input_vars?: int|string,
482
     *      max_multipart_body_parts?: int|string,
483
     *      post_max_size?: int|string,
484
     *      upload_max_filesize?: int|string,
485
     * }|null $options
486
     *
487
     * @throws RequestParseBodyException for errors when parsing the body
488
     *
489
     * @return array<int,array<mixed>>
490
     */
491
    protected function requestParseBody(?array $options = null) : array
492
    {
493
        return \request_parse_body($options);
1 ✔
494
    }
495

496
    public function isParsedBody() : bool
497
    {
498
        return isset($this->parsedBody);
22 ✔
499
    }
500

501
    /**
502
     * @return array{
503
     *      max_file_uploads?: int|string,
504
     *      max_input_vars?: int|string,
505
     *      max_multipart_body_parts?: int|string,
506
     *      post_max_size?: int|string,
507
     *      upload_max_filesize?: int|string,
508
     * }|null
509
     */
510
    public function getParseBodyOptions() : ?array
511
    {
512
        return $this->parseBodyOptions;
6 ✔
513
    }
514

515
    /**
516
     * @param array{
517
     *      max_file_uploads?: int|string,
518
     *      max_input_vars?: int|string,
519
     *      max_multipart_body_parts?: int|string,
520
     *      post_max_size?: int|string,
521
     *      upload_max_filesize?: int|string,
522
     * }|null $options
523
     *
524
     * @see https://www.php.net/manual/en/function.request-parse-body.php#refsect1-function.request-parse-body-parameters
525
     */
526
    public function setParseBodyOptions(?array $options) : static
527
    {
528
        $this->parseBodyOptions = $options;
1 ✔
529
        return $this;
1 ✔
530
    }
531

532
    /**
533
     * Get the request body as JSON.
534
     *
535
     * @param bool|null $associative When true, JSON objects will be returned as
536
     * associative arrays; when false, JSON objects will be returned as objects.
537
     * When null, JSON objects will be returned as associative arrays or objects
538
     * depending on whether JSON_OBJECT_AS_ARRAY is set in the flags.
539
     * @param int|null $flags [optional] <p>
540
     *  Bitmask consisting of <b>JSON_BIGINT_AS_STRING</b>,
541
     *  <b>JSON_INVALID_UTF8_IGNORE</b>,
542
     *  <b>JSON_INVALID_UTF8_SUBSTITUTE</b>,
543
     *  <b>JSON_OBJECT_AS_ARRAY</b>,
544
     *  <b>JSON_THROW_ON_ERROR</b>.
545
     *  </p>
546
     *  <p>Default is none when null.</p>
547
     * @param int<1,max> $depth user specified recursion depth
548
     *
549
     * @see https://www.php.net/manual/en/function.json-decode.php
550
     * @see https://www.php.net/manual/en/json.constants.php
551
     * @see Framework\HTTP\Message::getJsonFlags()
552
     * @see Framework\HTTP\Message::setJsonFlags()
553
     *
554
     * @return array<mixed>|false|stdClass If option JSON_THROW_ON_ERROR
555
     * is not set, return false if json_decode fail. Otherwise, return a
556
     * stdClass instance, or an array if the $associative argument is passed as
557
     * true.
558
     */
559
    public function getJson(
560
        ?bool $associative = null,
561
        ?int $flags = null,
562
        int $depth = 512
563
    ) : array | false | stdClass {
564
        if ($flags === null) {
2 ✔
565
            $flags = $this->getJsonFlags();
2 ✔
566
        }
567
        $body = \json_decode($this->getBody(), $associative, $depth, $flags);
2 ✔
568
        if (\json_last_error() !== \JSON_ERROR_NONE) {
2 ✔
569
            return false;
1 ✔
570
        }
571
        return $body;
1 ✔
572
    }
573

574
    /**
575
     * Get the Content-Type header value.
576
     *
577
     * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type
578
     *
579
     * @return string|null
580
     */
581
    public function getContentType() : ?string
582
    {
583
        return $this->getHeader(RequestHeader::CONTENT_TYPE);
2 ✔
584
    }
585

586
    /**
587
     * @param string|null $name
588
     * @param int|null $filter
589
     * @param array<int,int>|int $filterOptions
590
     *
591
     * @return mixed
592
     */
593
    public function getEnv(
594
        ?string $name = null,
595
        ?int $filter = null,
596
        array | int $filterOptions = 0
597
    ) : mixed {
598
        return $this->filterInput(\INPUT_ENV, $name, $filter, $filterOptions);
1 ✔
599
    }
600

601
    /**
602
     * @return array<string,UploadedFile|array<mixed>>
603
     */
604
    public function getFiles() : array
605
    {
606
        $this->prepareFiles();
4 ✔
607
        return $this->files;
4 ✔
608
    }
609

610
    public function hasFiles() : bool
611
    {
612
        $this->prepareFiles();
14 ✔
613
        return !empty($this->files);
14 ✔
614
    }
615

616
    public function getFile(string $name) : ?UploadedFile
617
    {
618
        $this->prepareFiles();
1 ✔
619
        $file = ArraySimple::value($name, $this->files);
1 ✔
620
        return \is_array($file) ? null : $file;
1 ✔
621
    }
622

623
    /**
624
     * Get the URL GET queries.
625
     *
626
     * @param string|null $name
627
     * @param int|null $filter
628
     * @param array<int,int>|int $filterOptions
629
     *
630
     * @see Framework\HTTP\Method::GET
631
     *
632
     * @return mixed
633
     */
634
    public function getGet(
635
        ?string $name = null,
636
        ?int $filter = null,
637
        array | int $filterOptions = 0
638
    ) : mixed {
639
        return $this->filterInput(\INPUT_GET, $name, $filter, $filterOptions);
1 ✔
640
    }
641

642
    /**
643
     * Get the X-Request-ID header.
644
     *
645
     * @return string|null
646
     */
647
    public function getId() : ?string
648
    {
649
        return $_SERVER['HTTP_X_REQUEST_ID'] ?? null;
2 ✔
650
    }
651

652
    #[Override]
653
    public function getMethod() : string
654
    {
655
        return parent::getMethod();
33 ✔
656
    }
657

658
    /**
659
     * @param string $method
660
     *
661
     * @throws InvalidArgumentException for invalid method
662
     *
663
     * @return bool
664
     */
665
    #[Override]
666
    public function isMethod(string $method) : bool
667
    {
668
        return parent::isMethod($method);
25 ✔
669
    }
670

671
    /**
672
     * Gets data from the last request, if it was redirected.
673
     *
674
     * @param string|null $key a key name or null to get all data
675
     *
676
     * @see Response::redirect()
677
     *
678
     * @throws LogicException if PHP Session is not active to get redirect data
679
     *
680
     * @return mixed an array containing all data, the key value or null
681
     * if the key was not found
682
     */
683
    public function getRedirectData(?string $key = null) : mixed
684
    {
685
        static $data;
4 ✔
686
        if ($data === null && \session_status() !== \PHP_SESSION_ACTIVE) {
4 ✔
687
            throw new LogicException('Session must be active to get redirect data');
1 ✔
688
        }
689
        if ($data === null) {
3 ✔
690
            $data = $_SESSION['$']['redirect_data'] ?? false;
3 ✔
691
            unset($_SESSION['$']['redirect_data']);
3 ✔
692
        }
693
        if ($key !== null && $data) {
3 ✔
694
            return ArraySimple::value($key, $data);
1 ✔
695
        }
696
        return $data === false ? null : $data;
3 ✔
697
    }
698

699
    /**
700
     * Get the URL port.
701
     *
702
     * @return int
703
     */
704
    public function getPort() : int
705
    {
706
        return (int) $_SERVER['SERVER_PORT'];
2 ✔
707
    }
708

709
    /**
710
     * Make an empty value according to the name type.
711
     *
712
     * @param string|null $name
713
     *
714
     * @return array<mixed>|null
715
     */
716
    protected function makeEmptyValue(?string $name) : ?array
717
    {
718
        return $name === null ? [] : null;
2 ✔
719
    }
720

721
    /**
722
     * Get POST data.
723
     *
724
     * Get data when the request method is POST and the Content-Type is
725
     * `application/x-www-form-urlencoded` or `multipart/form-data`.
726
     *
727
     * Files can be obtained using the {@see Framework\HTTP\Request::getFiles()}
728
     * method.
729
     *
730
     * @param string|null $name The array key name as a string, or null to return all data
731
     * @param int|null $filter Optional filter applied to the value returned with `$name`
732
     * @param array<int,int>|int $filterOptions Filter options
733
     *
734
     * @see Framework\HTTP\Method::POST
735
     *
736
     * @throws RequestParseBodyException for errors when parsing the body
737
     *
738
     * @return mixed Returns the value according to the `$name` and the filtering
739
     */
740
    public function getPost(
741
        ?string $name = null,
742
        ?int $filter = null,
743
        array | int $filterOptions = 0
744
    ) : mixed {
745
        if ($this->isEnabledPostDataReading()) {
10 ✔
746
            return $this->filterInput(\INPUT_POST, $name, $filter, $filterOptions);
10 ✔
747
        }
UNCOV
748
        if ($this->isMethod(Method::POST)) {
×
UNCOV
749
            return $this->getFilteredParsedBody($name, $filter, $filterOptions);
×
750
        }
UNCOV
751
        return $this->makeEmptyValue($name);
×
752
    }
753

754
    /**
755
     * Get PATCH data.
756
     *
757
     * Get data when the request method is PATCH and the Content-Type is
758
     * `application/x-www-form-urlencoded` or `multipart/form-data`.
759
     *
760
     * Files can be obtained using the {@see Framework\HTTP\Request::getFiles()}
761
     * method.
762
     *
763
     * @param string|null $name The array key name as a string, or null to return all data
764
     * @param int|null $filter Optional filter applied to the value returned with `$name`
765
     * @param array<int,int>|int $filterOptions Filter options
766
     *
767
     * @see Framework\HTTP\Method::PATCH
768
     *
769
     * @throws RequestParseBodyException for errors when parsing the body
770
     *
771
     * @return mixed Returns the value according to the `$name` and the filtering
772
     */
773
    public function getPatch(
774
        ?string $name = null,
775
        ?int $filter = null,
776
        array | int $filterOptions = 0
777
    ) : mixed {
778
        if ($this->isMethod(Method::PATCH)) {
1 ✔
779
            return $this->getFilteredParsedBody($name, $filter, $filterOptions);
1 ✔
780
        }
781
        return $this->makeEmptyValue($name);
1 ✔
782
    }
783

784
    /**
785
     * Get PUT data.
786
     *
787
     * Get data when the request method is PUT and the Content-Type is
788
     * `application/x-www-form-urlencoded` or `multipart/form-data`.
789
     *
790
     * Files can be obtained using the {@see Framework\HTTP\Request::getFiles()}
791
     * method.
792
     *
793
     * @param string|null $name The array key name as a string, or null to return all data
794
     * @param int|null $filter Optional filter applied to the value returned with `$name`
795
     * @param array<int,int>|int $filterOptions Filter options
796
     *
797
     * @see Framework\HTTP\Method::PUT
798
     *
799
     * @throws RequestParseBodyException for errors when parsing the body
800
     *
801
     * @return mixed Returns the value according to the `$name` and the filtering
802
     */
803
    public function getPut(
804
        ?string $name = null,
805
        ?int $filter = null,
806
        array | int $filterOptions = 0
807
    ) : mixed {
808
        if ($this->isMethod(Method::PUT)) {
1 ✔
809
            return $this->getFilteredParsedBody($name, $filter, $filterOptions);
1 ✔
810
        }
811
        return $this->makeEmptyValue($name);
1 ✔
812
    }
813

814
    /**
815
     * Get QUERY data.
816
     *
817
     * Get the response body when the request method is QUERY.
818
     *
819
     * @see Framework\HTTP\Method::QUERY
820
     *
821
     * @return string|null the request body or null if it is not a request with
822
     * the QUERY method
823
     */
824
    public function getQuery() : ?string
825
    {
826
        if ($this->isMethod(Method::QUERY)) {
1 ✔
827
            return $this->getBody();
1 ✔
828
        }
829
        return null;
1 ✔
830
    }
831

832
    /**
833
     * Get the Referer header.
834
     *
835
     * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer
836
     *
837
     * @return Url|null
838
     */
839
    public function getReferer() : ?Url
840
    {
841
        if ($this->referrer instanceof Url) {
2 ✔
842
            return $this->referrer;
1 ✔
843
        }
844
        if ($this->referrer === false) {
2 ✔
845
            return null;
2 ✔
846
        }
847
        $referer = $_SERVER['HTTP_REFERER'] ?? null;
2 ✔
848
        if ($referer === null) {
2 ✔
849
            $this->referrer = false;
1 ✔
850
            return null;
1 ✔
851
        }
852
        try {
853
            $this->referrer = new Url($referer);
2 ✔
854
        } catch (InvalidArgumentException) {
2 ✔
855
            $this->referrer = false;
2 ✔
856
        }
857
        return $this->getReferer();
2 ✔
858
    }
859

860
    /**
861
     * Get $_SERVER variables.
862
     *
863
     * @param string|null $name
864
     * @param int|null $filter
865
     * @param array<int,int>|int $filterOptions
866
     *
867
     * @return mixed
868
     */
869
    public function getServer(
870
        ?string $name = null,
871
        ?int $filter = null,
872
        array | int $filterOptions = 0
873
    ) : mixed {
874
        return $this->filterInput(\INPUT_SERVER, $name, $filter, $filterOptions);
13 ✔
875
    }
876

877
    /**
878
     * Gets the requested URL.
879
     *
880
     * @return Url
881
     */
882
    #[Override]
883
    public function getUrl() : Url
884
    {
885
        return parent::getUrl();
19 ✔
886
    }
887

888
    /**
889
     * Gets the User Agent client.
890
     *
891
     * @return UserAgent|null the UserAgent object or null if no user-agent
892
     * header was received
893
     */
894
    public function getUserAgent() : ?UserAgent
895
    {
896
        if ($this->userAgent instanceof UserAgent) {
14 ✔
897
            return $this->userAgent;
4 ✔
898
        }
899
        if ($this->userAgent === false) {
14 ✔
900
            return null;
11 ✔
901
        }
902
        $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? null;
14 ✔
903
        isset($userAgent)
14 ✔
904
            ? $this->setUserAgent($userAgent)
4 ✔
905
            : $this->userAgent = false;
11 ✔
906
        return $this->getUserAgent();
14 ✔
907
    }
908

909
    /**
910
     * @param UserAgent|string $userAgent
911
     *
912
     * @return static
913
     */
914
    protected function setUserAgent(UserAgent | string $userAgent) : static
915
    {
916
        if (!$userAgent instanceof UserAgent) {
4 ✔
917
            $userAgent = new UserAgent($userAgent);
4 ✔
918
        }
919
        $this->userAgent = $userAgent;
4 ✔
920
        return $this;
4 ✔
921
    }
922

923
    /**
924
     * Check if is an AJAX Request based in the X-Requested-With Header.
925
     *
926
     * The X-Requested-With Header containing the "XMLHttpRequest" value is
927
     * used by various JavaScript libraries.
928
     *
929
     * @return bool
930
     */
931
    public function isAjax() : bool
932
    {
933
        if (isset($this->isAjax)) {
2 ✔
934
            return $this->isAjax;
2 ✔
935
        }
936
        $received = $_SERVER['HTTP_X_REQUESTED_WITH'] ?? null;
2 ✔
937
        return $this->isAjax = ($received
2 ✔
938
            && \strtolower($received) === 'xmlhttprequest');
2 ✔
939
    }
940

941
    /**
942
     * Say if a connection has HTTPS.
943
     *
944
     * @return bool
945
     */
946
    public function isSecure() : bool
947
    {
948
        if (isset($this->isSecure)) {
187 ✔
949
            return $this->isSecure;
17 ✔
950
        }
951
        $scheme = $_SERVER['REQUEST_SCHEME'] ?? '';
187 ✔
952
        $https = $_SERVER['HTTPS'] ?? '';
187 ✔
953
        return $this->isSecure = (
187 ✔
954
            \strtolower($scheme) === 'https' || \strtolower($https) === 'on'
187 ✔
955
        );
187 ✔
956
    }
957

958
    /**
959
     * Tells if the Content-Type header is application/x-www-form-urlencoded.
960
     *
961
     * @return bool
962
     */
963
    public function isFormUrlEncoded() : bool
964
    {
965
        return $this->parseContentType() === 'application/x-www-form-urlencoded';
18 ✔
966
    }
967

968
    /**
969
     * Tells if the Content-Type header is multipart/form-data.
970
     *
971
     * @return bool
972
     */
973
    public function isFormData() : bool
974
    {
975
        return $this->parseContentType() === 'multipart/form-data';
7 ✔
976
    }
977

978
    /**
979
     * Tells if the Content-Type header is application/x-www-form-urlencoded or
980
     * multipart/form-data.
981
     *
982
     * @return bool
983
     */
984
    public function isForm() : bool
985
    {
986
        return $this->isFormUrlEncoded() || $this->isFormData();
6 ✔
987
    }
988

989
    /**
990
     * Say if the request is a JSON call.
991
     *
992
     * @return bool
993
     */
994
    public function isJson() : bool
995
    {
996
        return $this->parseContentType() === 'application/json';
1 ✔
997
    }
998

999
    /**
1000
     * Say if the request method is POST.
1001
     *
1002
     * @return bool
1003
     */
1004
    public function isPost() : bool
1005
    {
1006
        return $this->isMethod(Method::POST);
14 ✔
1007
    }
1008

1009
    /**
1010
     * @see https://php.watch/codex/enable_post_data_reading
1011
     *
1012
     * @return bool
1013
     */
1014
    protected function isEnabledPostDataReading() : bool
1015
    {
1016
        return \ini_get('enable_post_data_reading') === '1';
24 ✔
1017
    }
1018

1019
    /**
1020
     * @see https://www.sitepoint.com/community/t/-files-array-structure/2728/5
1021
     *
1022
     * @return array<string,UploadedFile|array<mixed>>
1023
     */
1024
    protected function getInputFiles() : array
1025
    {
1026
        if (!$this->isParsedBody() && !$this->isEnabledPostDataReading()) {
17 ✔
UNCOV
1027
            $this->parseBody($this->getParseBodyOptions());
×
1028
        }
1029
        $files = $this->parsedBody[1] ?? $_FILES;
17 ✔
1030
        if (empty($files)) {
17 ✔
1031
            return [];
14 ✔
1032
        }
1033
        $makeObjects = static function (
3 ✔
1034
            array $array,
3 ✔
1035
            callable $makeObjects
3 ✔
1036
        ) : UploadedFile | array {
3 ✔
1037
            $return = [];
3 ✔
1038
            foreach ($array as $k => $v) {
3 ✔
1039
                if (\is_array($v)) {
3 ✔
1040
                    $return[$k] = $makeObjects($v, $makeObjects);
3 ✔
1041
                    continue;
3 ✔
1042
                }
1043
                /**
1044
                 * @var array{
1045
                 *      name: string,
1046
                 *      type: string,
1047
                 *      tmp_name: string,
1048
                 *      error: int,
1049
                 *      size: int,
1050
                 *      full_path: string,
1051
                 * } $array
1052
                 */
1053
                return new UploadedFile($array);
3 ✔
1054
            }
1055
            return $return;
3 ✔
1056
        };
3 ✔
1057
        return $makeObjects(ArraySimple::files($files), $makeObjects); // @phpstan-ignore-line
3 ✔
1058
    }
1059

1060
    /**
1061
     * Make a Response with the current Request.
1062
     *
1063
     * @return Response
1064
     */
1065
    public function makeResponse() : Response
1066
    {
1067
        return new Response($this);
1 ✔
1068
    }
1069
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc