Skip to content

Commit

Permalink
Route - Get Data from the URL Path
Browse files Browse the repository at this point in the history
  • Loading branch information
duynx committed Jan 12, 2024
1 parent 41423d1 commit 4ce994c
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
4 changes: 4 additions & 0 deletions index.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,13 @@
});

$router = new Framework\Router();

$router->add("/product/{slug:[\w-]+}", ["controller" => "products", "action" => "show"]);
$router->add("/{controller}/{id:\d+}/{action}");
$router->add("/home/index", ["controller" => "home", "action" => "index"]);
$router->add("/products", ["controller" => "products", "action" => "index"]);
$router->add("/", ["controller" => "home", "action" => "index"]);
$router->add("/{controller}/{action}");

$params = $router->match($path);

Expand Down
36 changes: 33 additions & 3 deletions src/Framework/Router.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
class Router {
private array $routes = [];

public function add(string $path, array $params): void
public function add(string $path, array $params = []): void
{
$this->routes[] = [
"path" => $path,
Expand All @@ -14,12 +14,42 @@ public function add(string $path, array $params): void

public function match(string $path): array|bool
{
$path = urldecode($path);
$path = trim($path, "/");
foreach ($this->routes as $route) {
if($route["path"] === $path) {
return $route["params"];
$pattern = $this->getPatternFromRoutePath($route["path"]);

if (preg_match($pattern, $path, $matches)) {
$matches = array_filter($matches, "is_string", ARRAY_FILTER_USE_KEY);
$params = array_merge($matches, $route["params"]);

return $params;
}

}

return false;
}

private function getPatternFromRoutePath(string $routePath): string
{
$routePath = trim($routePath, "/");
$segments = explode("/", $routePath);

$segments = array_map(function (string $segment): string {

if(preg_match("#^\{([a-z][a-z0-9]*)\}$#", $segment, $matches)) {
return "(?<" . $matches[1] . ">[^/]*)";
}

if(preg_match("#^\{([a-z][a-z0-9]*):(.+)\}$#", $segment, $matches)) {
return "(?<" . $matches[1] . ">". $matches[2]. ")";
}

return $segment;

}, $segments);

return "#^" . implode("/", $segments) . "$#iu";
}
}

0 comments on commit 4ce994c

Please sign in to comment.