iwa-panda1

Manage Weather Data by International Weather Agency (Version 1)
Log | Files | Refs

Router.php (1262B)


      1 <?php
      2 
      3 namespace Lollipop {
      4 	class Router
      5 	{
      6 		protected array $routes = [];
      7 		protected string $path;
      8 
      9 		protected function match(string $match, array &$route_vars): bool
     10 		{
     11 			$route_split = explode('/', $this->path);
     12 			$match_split = explode('/', $match);
     13 
     14 			if (sizeof($route_split) != sizeof($match_split)) {
     15 				return false;
     16 			}
     17 
     18 			foreach ($match_split as $index => $m) {
     19 				if (str_starts_with($m, ':')) {
     20 					$route_vars[substr($m, 1)] = $route_split[$index];
     21 				} else if ($m != $route_split[$index]) {
     22 					return false;
     23 				}
     24 			}
     25 			return true;
     26 		}
     27 
     28 
     29 		function addRoute(string $method, string $match, callable $func)
     30 		{
     31 			$this->routes[] = array(
     32 				"method" => $method,
     33 				"match" => $match,
     34 				"func" => $func,
     35 			);
     36 		}
     37 
     38 		function route(string $base = null)
     39 		{
     40 			$this->path = $_SERVER["REQUEST_URI"];
     41 
     42 			if ($base && strpos($this->path, $base))
     43 				$this->path = explode($base, $this->path)[1];
     44 
     45 			$method = $_SERVER["REQUEST_METHOD"];
     46 
     47 			foreach ($this->routes as $route) {
     48 				if ($route["method"] != null && $route["method"] != $method)
     49 					continue;
     50 
     51 				$vars = [];
     52 				if ($this->match($route["match"], $vars))
     53 					return $route["func"]($vars);
     54 			}
     55 
     56 			echo "404 '$this->path' not found!";
     57 			return null;
     58 		}
     59 	}
     60 }