Skip to content
This repository has been archived by the owner on Aug 1, 2021. It is now read-only.

Commit

Permalink
Added wildcard support
Browse files Browse the repository at this point in the history
  • Loading branch information
o-alquimista committed Mar 24, 2020
1 parent 6813be6 commit 8ee3774
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 2 deletions.
17 changes: 17 additions & 0 deletions src/Fragments/Component/Routing/Model/Route.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@ class Route
*/
private $methods;

/**
* Route parameters injected by the router.
*/
private $parameters;

public function getId(): string
{
return $this->id;
Expand Down Expand Up @@ -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;
}
}
39 changes: 37 additions & 2 deletions src/Fragments/Component/Routing/Router.php
Original file line number Diff line number Diff line change
Expand Up @@ -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())) {
Expand All @@ -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
Expand Down

0 comments on commit 8ee3774

Please sign in to comment.