Request::isMethod()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 6
ccs 2
cts 2
cp 1
crap 1
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gacela\Router\Entities;
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
19
    public const ALL_METHODS = [
20
        self::METHOD_CONNECT,
21
        self::METHOD_DELETE,
22
        self::METHOD_GET,
23
        self::METHOD_HEAD,
24
        self::METHOD_OPTIONS,
25
        self::METHOD_PATCH,
26
        self::METHOD_POST,
27
        self::METHOD_PUT,
28
        self::METHOD_TRACE,
29
    ];
30
31 112
    /**
32
     * @param array<string, mixed> $query
33
     * @param array<string, mixed> $request
34
     * @param array<string, mixed> $server
35
     */
36 112
    private function __construct(
37
        private array $query,
38 112
        private array $request,
39
        private array $server,
40 112
    ) {
41
    }
42
43 102
    public static function fromGlobals(): self
44
    {
45
        /** @var array<string, mixed> $get */
46 102
        $get = $_GET;
47
        /** @var array<string, mixed> $post */
48 102
        $post = $_POST;
49
        /** @var array<string, mixed> $server */
50
        $server = $_SERVER;
51 97
52
        return new self($get, $post, $server);
53
    }
54 97
55
    public function isMethod(string $method): bool
56 97
    {
57
        /** @var string $requestMethod */
58 97
        $requestMethod = $this->server['REQUEST_METHOD'];
59
60
        return $requestMethod === $method;
61 2
    }
62
63
    public function path(): string
64 2
    {
65
        /** @var string $requestUri */
66 2
        $requestUri = $this->server['REQUEST_URI'];
67 2
        /** @var string $parsedUrl */
68
        $parsedUrl = parse_url($requestUri, PHP_URL_PATH);
69
70
        return $parsedUrl;
71
    }
72
73
    public function get(string $key, mixed $default = null): mixed
74
    {
75
        /** @var mixed $result */
76
        $result = $this->request[$key] ?? $this->query[$key] ?? null;
77
78
        if ($result !== null) {
79
            return $result;
80
        }
81
82
        return $default;
83
    }
84
}
85