hanze/iwa-panda1

utils/router.php in tak
Repositories | Summary | Log | Files

router.php (1566B) download


 1<?php
 2
 3class 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        if ($query != null) {
55            parse_str($query, $_GET);
56        }
57
58		if (strpos($this->path, '?'))
59			$this->path = explode('?', $this->path)[0];
60
61		$method = $_SERVER["REQUEST_METHOD"];
62
63		foreach ($this->routes as $route) {
64			if ($route["method"] != null && !in_array($method, $route["method"]))
65				continue;
66
67			$vars = [];
68			if ($this->match($route["match"], $vars)) {
69				return $this->includeRoute($route["func"], $vars);
70			}
71		}
72
73		return $this->includeRoute($not_found_handler, $vars);
74	}
75}