3
namespace Engine\Core\Router;
10
private array $methods = [
18
private array $routes = [
26
private array $patterns = [
28
'str' => '[a-zA-Z\.\-_%]+',
29
'any' => '[a-zA-Z0-9\.\-_%]+'
36
public function addPattern($key, $pattern): void
38
$this->patterns[$key] = $pattern;
45
public function routes($method): array
47
return $this->routes[$method] ?? [];
55
public function register($method, $pattern, $controller): void
57
$transfer = $this->transferPattern($pattern);
59
$this->routes[strtoupper($method)][$transfer] = $controller;
64
* @return string|string[]|null
66
private function transferPattern($pattern): array|string|null
68
if(!str_contains($pattern, '(')) {
72
return preg_replace_callback(
74
[$this, 'replacePattern'],
83
private function replacePattern($matches): string
85
return '(?<' .$matches[1]. '>' . strtr($matches[2], $this->patterns) . ')';
92
private function processParam($parameters): mixed
94
foreach ($parameters as $index => $parameter)
98
unset($parameters[$index]);
108
* @return DispatchedRoute
110
public function dispatch($method, $uri): DispatchedRoute
112
$routes = $this->routes(strtoupper($method));
114
if(array_key_exists($uri, $routes)) {
115
return new DispatchedRoute($routes[$uri]);
118
return $this->doDispatch($method, $uri);
124
* @return DispatchedRoute
126
private function doDispatch($method, $uri): DispatchedRoute
128
foreach ($this->routes($method) as $route => $controller) {
129
$pattern = '#^' . $route . '$#s';
131
if(preg_match($pattern, $uri, $parameters))
133
return new DispatchedRoute($controller, $this->processParam($parameters));