corso https://vola.udemy.com/course/php-mvc-from-scratch/learn/lecture/40931984#overview
filippo.bertilotti
2024-05-17 a212c53dc537ce66800b8e987fb18b1aab994bb4
commit | author | age
c958d0 1 <?php
7301d1 2 namespace Framework;
c958d0 3
F 4 class Router {
5     private array $routes = [];
6     
7     public function add(string $path, array $params = []): void {
8         $this->routes[] = [
9             "path"=> $path,
10             "params"=> $params
11         ];
12
931be5 13
F 14     }
2272ef 15     public function match (string $path): array|bool {
F 16         $path = urldecode($path);
17         
274930 18         $path = trim($path, "/");   
F 19
38b8de 20         foreach ($this->routes as $route) {
F 21
274930 22             $pattern = $this->getPatternFromRoutePath($route["path"]);
2d9ddb 23
38b8de 24             if(preg_match($pattern, $path, $matches)) {
F 25                 $matches = array_filter($matches, "is_string", ARRAY_FILTER_USE_KEY);
7adeb4 26
F 27                 $params = array_merge($matches, $route["params"]);
28
29                 return $params;
38b8de 30             }
82846a 31         }
F 32         
865a53 33         return false;
F 34     }
38b8de 35
274930 36     private function getPatternFromRoutePath(string $route_path): string {
865a53 37         $route_path = trim("$route_path", "/");
F 38
39         $segments = explode("/", $route_path);
40         
41         $segments = array_map(function(string $segment) :string {
2d9ddb 42
7adeb4 43             if(preg_match("#^\{([a-z][a-z0-9]*)\}$#", $segment, $matches)) {
c0c5ce 44                 return "(?<" . $matches[1] . ">[^/]*)";
F 45             }
46             if(preg_match("#^\{([a-z][a-z0-9]*):(.+)\}$#", $segment, $matches)) {
47                 return "(?<" . $matches[1] . ">". $matches[2] ."[^/]*)";
7adeb4 48             }
865a53 49             return $segment;
F 50         }, $segments);
2d9ddb 51
2272ef 52         return "#^" . implode("/", $segments) . "$#iu";
c958d0 53     }
F 54 }