hanze/lollipop

Lollipop/Router.php in views
Repositories | Summary | Log | Files

Router.php (1627B) download


 1<?php
 2
 3namespace 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|array $method, string $match, string|callable $func)
30		{
31			if (is_string($method))
32				$method = [$method];
33
34
35			$this->routes[] = array(
36				"method" => $method,
37				"match" => $match,
38				"func" => $func,
39			);
40		}
41
42		function includeRoute(string $path, array $_PARAM)
43		{
44			include $path;
45		}
46
47		function route(string $base = null)
48		{
49			$this->path = $_SERVER["REQUEST_URI"];
50
51			if (strpos($this->path, '?'))
52				$this->path = explode('?', $this->path)[0];
53
54			if ($base && strpos($this->path, $base))
55				$this->path = explode($base, $this->path)[1];
56
57			$method = $_SERVER["REQUEST_METHOD"];
58
59			foreach ($this->routes as $route) {
60				if ($route["method"] != null && !in_array($method, $route["method"]))
61					continue;
62
63				$vars = [];
64				if ($this->match($route["match"], $vars)) {
65					if (is_callable($route["func"])) {
66						return $route["func"]($vars);
67					} else {
68						return $this->includeRoute($route["func"], $vars);
69					}
70				}
71			}
72
73			echo "404 '$this->path' not found!";
74			return null;
75		}
76	}
77}