From ce9b2119ceb911faab15fa43e741d63e3fb7834c Mon Sep 17 00:00:00 2001 From: filippo.bertilotti <filippobertilotti@gmail.com> Date: Tue, 21 May 2024 10:09:46 +0200 Subject: [PATCH] aggiunto ref a ogni product e aggiunta eccezione di prodotto non trovato in caso non esista nel database (parte 119) --- src/Framework/router.php | 41 ++++++++++++++++++++++++++++++++--------- 1 files changed, 32 insertions(+), 9 deletions(-) diff --git a/src/Framework/router.php b/src/Framework/router.php index b6d8eeb..63596c4 100644 --- a/src/Framework/router.php +++ b/src/Framework/router.php @@ -12,20 +12,43 @@ } - public function match (string $path,): array|bool { + public function match (string $path): array|bool { + $path = urldecode($path); - $pattern = "#^/(?<controller>[a-z]+)/(?<action>[a-z]+)$#"; + $path = trim($path, "/"); - if(preg_match($pattern, $path, $matches)) { - print_r($matches); - exit("Match"); - } - 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 $route_path): string { + $route_path = trim("$route_path", "/"); + + $segments = explode("/", $route_path); + + $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"; + } } \ No newline at end of file -- Gitblit v1.8.0