commit | author | age
|
15e03a
|
1 |
<?php |
F |
2 |
namespace Framework; |
|
3 |
|
|
4 |
class Router { |
|
5 |
private array $routes = []; |
|
6 |
|
|
7 |
public function add(string $path, array $params = []): void { |
|
8 |
$this->routes[] = [ |
|
9 |
"path"=> $path, |
|
10 |
"params"=> $params |
|
11 |
]; |
|
12 |
|
|
13 |
|
|
14 |
} |
|
15 |
public function match (string $path, string $method): array|bool { |
|
16 |
$path = urldecode($path); |
|
17 |
|
|
18 |
$path = trim($path, "/"); |
|
19 |
|
|
20 |
foreach ($this->routes as $route) { |
|
21 |
|
|
22 |
$pattern = $this->getPatternFromRoutePath($route["path"]); |
|
23 |
|
|
24 |
if(preg_match($pattern, $path, $matches)) { |
|
25 |
$matches = array_filter($matches, "is_string", ARRAY_FILTER_USE_KEY); |
|
26 |
|
|
27 |
$params = array_merge($matches, $route["params"]); |
|
28 |
|
|
29 |
if(array_key_exists("method", $params)) { |
|
30 |
if(strtolower($method) !== strtolower($params["method"])) { |
|
31 |
continue; |
|
32 |
} |
|
33 |
} |
|
34 |
|
|
35 |
return $params; |
|
36 |
} |
|
37 |
} |
|
38 |
|
|
39 |
return false; |
|
40 |
} |
|
41 |
|
|
42 |
private function getPatternFromRoutePath(string $route_path): string { |
|
43 |
$route_path = trim("$route_path", "/"); |
|
44 |
|
|
45 |
$segments = explode("/", $route_path); |
|
46 |
|
|
47 |
$segments = array_map(function(string $segment) :string { |
|
48 |
|
|
49 |
if(preg_match("#^\{([a-z][a-z0-9]*)\}$#", $segment, $matches)) { |
|
50 |
return "(?<" . $matches[1] . ">[^/]*)"; |
|
51 |
} |
|
52 |
if(preg_match("#^\{([a-z][a-z0-9]*):(.+)\}$#", $segment, $matches)) { |
|
53 |
return "(?<" . $matches[1] . ">". $matches[2] ."[^/]*)"; |
|
54 |
} |
|
55 |
return $segment; |
|
56 |
}, $segments); |
|
57 |
|
|
58 |
return "#^" . implode("/", $segments) . "$#iu"; |
|
59 |
} |
|
60 |
} |