lollipop

A PHP-framework
Log | Files | Refs

commit 9c461e90d214fd080834e431c6f9879d76b2edac
parent f61c789548b74fbcd8fd5c1aadf49aab1b24759e
Author: Friedel Schon <[email protected]>
Date:   Tue, 11 Apr 2023 11:54:44 +0200

adding Router.php

Diffstat:
ARouter.php | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 57 insertions(+), 0 deletions(-)

diff --git a/Router.php b/Router.php @@ -0,0 +1,56 @@ +<?php + +class Router +{ + protected array $routes = []; + protected string $route; + + protected function match(string $match, array &$route_vars): bool + { + $route_split = explode('/', $this->route); + $match_split = explode('/', $match); + + if (sizeof($route_split) != sizeof($match_split)) { + return false; + } + + foreach ($match_split as $index => $m) { + if (str_starts_with($m, ':')) { + $route_vars[substr($m, 1)] = $route_split[$index]; + } else if ($m != $route_split[$index]) { + return false; + } + } + return true; + } + + + function addRoute(string $method, string $match, callable $func) + { + $this->routes[] = array( + "method" => $method, + "match" => $method, + "func" => $func, + ); + } + + function route(string $base = null) + { + $this->route = $_SERVER["REQUEST_URI"]; + + if ($base && strpos($this->route, $base)) + $this->route = explode($base, $this->route)[1]; + + $method = $_SERVER["REQUEST_METHOD"]; + + foreach ($this->routes as $route) { + if ($route["method"] != null && $route["method"] != $method) + continue; + + $vars = []; + if ($this->match($route["match"], $vars)) + return $route["func"]($vars); + } + return null; + } +} +\ No newline at end of file