corso https://vola.udemy.com/course/php-mvc-from-scratch/learn/lecture/40931984#overview
filippo.bertilotti
2024-05-27 61ad98a6e2914578cae32f249d2b496892c0f10b
src/Framework/router.php
@@ -12,37 +12,49 @@
    }
    public function match (string $path,): array|bool {
    public function match (string $path, string $method): array|bool {
        $path = urldecode($path);
        $path = trim($path, "/");
        foreach ($this->routes as $route) {
            $pattern = "#^/(?<controller>[a-z]+)/(?<action>[a-z]+)$#";
            echo $pattern, "\n", $route["path"],"\n";
            $this->getPatternFromRoutePath($route["path"]);
            $pattern = $this->getPatternFromRoutePath($route["path"]);
            if(preg_match($pattern, $path, $matches)) {
                $matches = array_filter($matches, "is_string", ARRAY_FILTER_USE_KEY);
                return $matches;
                $params = array_merge($matches, $route["params"]);
                if(array_key_exists("method", $params)) {
                    if(strtolower($method) !== strtolower($params["method"])) {
                        continue;
                    }
                }
                return $params;
            }
        }
        
        return false;
    }
    private function getPatternFromRoutePath(string $route_path) {
    private function getPatternFromRoutePath(string $route_path): string {
        $route_path = trim("$route_path", "/");
        $segments = explode("/", $route_path);
        
        $segments = array_map(function(string $segment) :string {
            preg_match("#^\{([a-z][a-z0-9]*)\}$#", $segment, $matches);
            $segment = "(?<" . $matches[1] . ">[a-z]+)";
            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);
        print_r($segments);
        return "#^" . implode("/", $segments) . "$#iu";
    }
}