Total Complexity | 7 |
Total Lines | 73 |
Duplicated Lines | 0 % |
Changes | 1 | ||
Bugs | 1 | Features | 0 |
1 | <?php |
||
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 |
||
85 | } |
||
86 | } |
||
87 |