corso https://vola.udemy.com/course/php-mvc-from-scratch/learn/lecture/40931984#overview
filippo.bertilotti
2024-05-21 ce9b2119ceb911faab15fa43e741d63e3fb7834c
src/Framework/router.php
@@ -1,4 +1,5 @@
<?php
namespace Framework;
class Router {
    private array $routes = [];
@@ -11,12 +12,43 @@
    }
    public function match (string $path,): array|bool {
    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 $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";
    }
}