Request   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 76
Duplicated Lines 0 %

Test Coverage

Coverage 93.75%

Importance

Changes 5
Bugs 0 Features 0
Metric Value
eloc 33
dl 0
loc 76
ccs 15
cts 16
cp 0.9375
rs 10
c 5
b 0
f 0
wmc 6

5 Methods

Rating   Name   Duplication   Size   Complexity  
A isMethod() 0 6 1
A get() 0 10 2
A fromGlobals() 0 10 1
A path() 0 8 1
A __construct() 0 5 1
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