corso https://vola.udemy.com/course/php-mvc-from-scratch/learn/lecture/40931984#overview
filippo.bertilotti
2024-05-15 75438d3b6c46f9566ff7f6a9657dda7cdfbf9a6d
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
<?php
namespace Framework;
 
class Router {
    private array $routes = [];
    
    public function add(string $path, array $params = []): void {
        $this->routes[] = [
            "path"=> $path,
            "params"=> $params
        ];
 
 
    }
    public function match (string $path): array|bool {
        $path = urldecode($path);
        
        $path = trim($path, "/");   
 
        foreach ($this->routes as $route) {
 
            $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";
    }
}