router.php (1516B)
1 <?php 2 3 class Router 4 { 5 protected array $routes = []; 6 protected string $path; 7 8 protected function match(string $match, array &$route_vars): bool 9 { 10 $route_split = explode('/', $this->path); 11 $match_split = explode('/', $match); 12 13 if (sizeof($route_split) != sizeof($match_split)) { 14 return false; 15 } 16 17 foreach ($match_split as $index => $m) { 18 if (str_starts_with($m, ':')) { 19 $route_vars[substr($m, 1)] = $route_split[$index]; 20 } else if ($m != $route_split[$index]) { 21 return false; 22 } 23 } 24 return true; 25 } 26 27 28 function addRoute(string|array $method, string $match, string|callable $func) 29 { 30 if (is_string($method)) 31 $method = [$method]; 32 33 34 $this->routes[] = array( 35 "method" => $method, 36 "match" => $match, 37 "func" => $func, 38 ); 39 } 40 41 function includeRoute(string $path, array $_PARAM) 42 { 43 if (is_callable($path)) 44 return $path($_PARAM); 45 else 46 include $path; 47 } 48 49 function route(string|callable $not_found_handler) 50 { 51 $this->path = $_SERVER["REQUEST_URI"]; 52 53 $query = parse_url($this->path, PHP_URL_QUERY); 54 parse_str($query, $_GET); 55 56 if (strpos($this->path, '?')) 57 $this->path = explode('?', $this->path)[0]; 58 59 $method = $_SERVER["REQUEST_METHOD"]; 60 61 foreach ($this->routes as $route) { 62 if ($route["method"] != null && !in_array($method, $route["method"])) 63 continue; 64 65 $vars = []; 66 if ($this->match($route["match"], $vars)) { 67 return $this->includeRoute($route["func"], $vars); 68 } 69 } 70 71 return $this->includeRoute($not_found_handler, $vars); 72 } 73 }