Tim
2fd6e50b90
diff --git a/src/Http/GenericRouter.php b/src/Http/GenericRouter.php index 23e9311..d5ffb95 100644 --- a/src/Http/GenericRouter.php +++ b/src/Http/GenericRouter.php @@ -22,16 +22,47 @@ class GenericRouter implements RouterInterface public function dispatch(RequestInterface $request): ResponseInterface { foreach ($this->config->getRoutes() as $route) { - if ($route->getRoute()->path === $request->getUri()) { - $controller = $this->container->get($route->getController()); - $method = $route->getMethod(); - return $controller->$method(...$this->autowire($route)); + $params = $this->resolveParams($route->getRoute()->path, $request->getUri()); + + if ($params === null) { + continue; } + + $controller = $this->container->get($route->getController()); + $method = $route->getMethod(); +// $params = $this->autowire($route) + $this->resolveParams($route->getRoute()->path, $request->getUri()); + $params = $this->resolveParams($route->getRoute()->path, $request->getUri()); + return $controller->$method(...$params); } throw new RouteNotFoundException($request); } + private function resolveParams(string $routeUri, string $requestUri): ?array + { + $result = preg_match_all('/{(\w+)}/', $routeUri, $tokens); + + if (!$result) { + return null; + } + + $tokens = $tokens[0]; + + $matchingRegex = '/^' . str_replace( + ['/', ...$tokens], + ['\/', ...array_fill(0, count($tokens), '([\w\s]+)')], + $routeUri + ) . '$/'; + + $result = preg_match($matchingRegex, $requestUri, $matches); + if ($result === 0) { + return []; + } + $matches = array_slice($matches, 1); + + return array_combine(array_map(fn($token) => trim($token, '{}'), $tokens), $matches); + } + private function autowire(RouteConfig $route): array { $reflectionMethod = new ReflectionMethod($route->getController(), $route->getMethod()); |
||
---|---|---|
app | ||
public | ||
src | ||
.gitignore | ||
composer.json | ||
composer.lock | ||
README.md |
Simple PHP micro framework
Current features:
- Routing with method dependency injection
- Controller configuration with annotations
- Dependency injection application configuration