Passed
Pull Request — main (#2)
by Chema
02:25
created

Request::instance()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 6
ccs 4
cts 4
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gacela\Router;
6
7
final class Request
8
{
9
    public const METHOD_CONNECT = 'CONNECT';
10
    public const METHOD_DELETE = 'DELETE';
11
    public const METHOD_GET = 'GET';
12
    public const METHOD_HEAD = 'HEAD';
13
    public const METHOD_OPTIONS = 'OPTIONS';
14
    public const METHOD_PATCH = 'PATCH';
15
    public const METHOD_POST = 'POST';
16
    public const METHOD_PUT = 'PUT';
17
    public const METHOD_TRACE = 'TRACE';
18
    private static ?self $instance = null;
19
20 42
    private function __construct(
21
        private array $query,
22
        private array $request,
23
        private array $server,
24
    ) {
25 42
    }
26
27 42
    public static function resetCache(): void
28
    {
29 42
        self::$instance = null;
30
    }
31
32 42
    public static function instance(): self
33
    {
34 42
        if (self::$instance === null) {
35 42
            self::$instance = new self($_GET, $_POST, $_SERVER);
36
        }
37 42
        return self::$instance;
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::instance could return the type null which is incompatible with the type-hinted return Gacela\Router\Request. Consider adding an additional type-check to rule them out.
Loading history...
38
    }
39
40 42
    public function isMethod(string $method): bool
41
    {
42
        /** @psalm-suppress PossiblyUndefinedArrayOffset */
43 42
        return (string)$this->server['REQUEST_METHOD'] === $method;
44
    }
45
46 41
    public function path(): string
47
    {
48
        /** @psalm-suppress PossiblyUndefinedArrayOffset */
49 41
        return (string)parse_url(
50 41
            (string)$this->server['REQUEST_URI'],
51 41
            PHP_URL_PATH,
52 41
        );
53
    }
54
55
    public function get(string $key): mixed
56
    {
57
        return $this->request[$key]
58
            ?? $this->query[$key]
59
            ?? null;
60
    }
61
}
62