|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace PhpLightning\Router; |
|
6
|
|
|
|
|
7
|
|
|
use function call_user_func_array; |
|
8
|
|
|
use function count; |
|
9
|
|
|
|
|
10
|
|
|
final class Router |
|
11
|
|
|
{ |
|
12
|
|
|
public function __construct( |
|
13
|
|
|
private string $requestMethod, |
|
14
|
|
|
private string $requestUri, |
|
15
|
|
|
) { |
|
16
|
|
|
} |
|
17
|
|
|
|
|
18
|
|
|
public function get(string $route, callable $callback): void |
|
19
|
|
|
{ |
|
20
|
|
|
if ($this->requestMethod === 'GET') { |
|
21
|
|
|
$this->route($route, $callback); |
|
22
|
|
|
} |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
private function route(string $route, callable $callback): void |
|
26
|
|
|
{ |
|
27
|
|
|
$requestUrl = $this->requestUrl(); |
|
28
|
|
|
$routeParts = explode('/', $route); |
|
29
|
|
|
$requestUrlParts = explode('/', $requestUrl); |
|
30
|
|
|
array_shift($routeParts); |
|
31
|
|
|
array_shift($requestUrlParts); |
|
32
|
|
|
|
|
33
|
|
|
if ($routeParts[0] === '' && count($requestUrlParts) === 0) { |
|
34
|
|
|
call_user_func_array($callback, []); |
|
35
|
|
|
exit(); |
|
|
|
|
|
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
if (count($routeParts) !== count($requestUrlParts)) { |
|
39
|
|
|
return; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
$parameters = $this->parameters($routeParts, $requestUrlParts); |
|
43
|
|
|
if ($parameters === []) { |
|
44
|
|
|
return; |
|
45
|
|
|
} |
|
46
|
|
|
call_user_func_array($callback, $parameters); |
|
47
|
|
|
exit(); |
|
|
|
|
|
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
private function requestUrl(): string |
|
51
|
|
|
{ |
|
52
|
|
|
$requestUrl = (string)filter_var($this->requestUri, FILTER_SANITIZE_URL); |
|
53
|
|
|
$requestUrl = rtrim($requestUrl, '/'); |
|
54
|
|
|
|
|
55
|
|
|
return (string)strtok($requestUrl, '?'); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* @psalm-suppress MixedAssignment,MixedArgument |
|
60
|
|
|
*/ |
|
61
|
|
|
private function parameters(array $routeParts, array $requestUrlParts): array |
|
62
|
|
|
{ |
|
63
|
|
|
$parameters = []; |
|
64
|
|
|
for ($i = 0, $iMax = count($routeParts); $i < $iMax; ++$i) { |
|
65
|
|
|
$routePart = $routeParts[$i]; |
|
66
|
|
|
if (preg_match('/^[$]/', $routePart)) { |
|
67
|
|
|
$routePart = ltrim($routePart, '$'); |
|
68
|
|
|
$parameters[] = $requestUrlParts[$i]; |
|
69
|
|
|
$$routePart = $requestUrlParts[$i]; |
|
70
|
|
|
} elseif ($routeParts[$i] !== $requestUrlParts[$i]) { |
|
71
|
|
|
return []; |
|
72
|
|
|
} |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
|
|
return $parameters; |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|
In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.