diff --git a/src/Fragments/Component/Routing/Model/Route.php b/src/Fragments/Component/Routing/Model/Route.php index 4ec3f73..453bb31 100644 --- a/src/Fragments/Component/Routing/Model/Route.php +++ b/src/Fragments/Component/Routing/Model/Route.php @@ -48,6 +48,11 @@ class Route */ private $methods; + /** + * Route parameters injected by the router. + */ + private $parameters; + public function getId(): string { return $this->id; @@ -109,4 +114,16 @@ public function setMethods(string $methods) return $this; } + + public function getParameters(): ?array + { + return $this->parameters; + } + + public function setParameters(array $parameters) + { + $this->parameters = $parameters; + + return $this; + } } diff --git a/src/Fragments/Component/Routing/Router.php b/src/Fragments/Component/Routing/Router.php index ac5557c..f730abd 100644 --- a/src/Fragments/Component/Routing/Router.php +++ b/src/Fragments/Component/Routing/Router.php @@ -51,7 +51,36 @@ private function matchRoute(array $routes): Route { foreach ($routes as $route) { if ($route->getPath() != $this->request->getURI()) { - continue; + $routePath = $route->getPath(); + + // Are there any wildcards in the route path? + if (!preg_match('/{(\w+)}/', $routePath)) { + continue; + } + + // Replace all wildcards with capturing groups + $regex = preg_replace('/{(\w+)}/', '(\w+)', $routePath); + + // Escape forward slashes in the path + $regex = preg_replace('/\//', '\/', $regex); + + // Add start and end regex delimiters + $regex = '/^' . $regex . '$/'; + + if (preg_match($regex, $this->request->getURI(), $matches)) { + // The first item is not a wildcard value, so remove it + array_shift($matches); + + $parameters = []; + + foreach ($matches as $parameter) { + $parameters[] = $parameter; + } + + $route->setParameters($parameters); + } else { + continue; + } } if (!in_array($this->request->requestMethod(), $route->getMethods())) { @@ -68,9 +97,15 @@ private function load(Route $route) { $controller = $route->getController(); $action = $route->getAction(); + $parameters = $route->getParameters(); $controller = new $controller; - $controller->{$action}(); + + if ($parameters) { + $controller->{$action}(...$parameters); + } else { + $controller->{$action}(); + } } private function getRouteById(string $routeId): Route