progetto fatto precedentemente adattato al framework creato con il corso
filippo.bertilotti
2024-06-05 15e03a88fa42f2444138ebc6f171c9a32a3a4238
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
55
56
57
58
59
60
<?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, string $method): 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"]);
 
                if(array_key_exists("method", $params)) {
                    if(strtolower($method) !== strtolower($params["method"])) {
                        continue;
                    }
                }
 
                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";
    }
}