Route::url()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace alkemann\h2l;
4
5
use alkemann\h2l\exceptions\InvalidCallback;
6
7
/**
8
 * Class Route
9
 *
10
 * @package alkemann\h2l
11
 */
12
class Route implements interfaces\Route
13
{
14
    /**
15
     * @var string
16
     */
17
    private string $url;
18
    /**
19
     * @var callable
20
     */
21
    private $callback;
22
    /**
23
     * @var array<string, mixed>
24
     */
25
    private array $parameters;
26
27
    /**
28
     * Route constructor.
29
     *
30
     * @param string $url
31
     * @param callable $cb
32
     * @param array<string, mixed> $parameters
33
     */
34
    public function __construct(string $url, callable $cb, array $parameters = [])
35
    {
36
        $this->url = $url;
37
        $this->callback = $cb;
38
        $this->parameters = $parameters;
39
    }
40
41
    /**
42
     *  Returns the url that the route was created for/with
43
     *
44
     * @return string
45
     */
46
    public function url(): string
47
    {
48
        return $this->url;
49
    }
50
51
    /**
52
     * Returns all the parameters that the route was created with
53
     *
54
     * @return array<string, mixed>
55
     */
56
    public function parameters(): array
57
    {
58
        return $this->parameters;
59
    }
60
61
    /**
62
     * Converts the Route to a Response that can be rendered for the final output
63
     *
64
     * @param Request $request
65
     * @return Response|null
66
     * @throws InvalidCallback if callback did not return Response|null
67
     */
68
    public function __invoke(Request $request): ?Response
69
    {
70
        $response = call_user_func_array($this->callback, [$request]);
71
        if (is_null($response) || $response instanceof Response) {
72
            return $response;
73
        }
74
        throw new InvalidCallback("Route callbacks must only return null or a subclass of alkemann\h2l\Response");
75
    }
76
77
    /**
78
     * Returns the URL (after domain) of the route
79
     *
80
     * @return string
81
     */
82
    public function __toString(): string
83
    {
84
        return $this->url;
85
    }
86
}
87