forked from PHP/Router
43 lines
1.1 KiB
PHP
43 lines
1.1 KiB
PHP
<?php
|
|
|
|
class StaticRouter
|
|
{
|
|
public static $routes = [];
|
|
|
|
public static function add(string $method, string $route, callable $handler): void
|
|
{
|
|
$segments = array_map(function($segment) {
|
|
return str_starts_with($segment, ':') ? ':x' : $segment;
|
|
}, explode('/', trim($route, '/')));
|
|
|
|
$node = &self::$routes;
|
|
foreach ($segments as $segment) {
|
|
if ($segment === '') continue;
|
|
$node = &$node[$segment];
|
|
}
|
|
|
|
$node[$method] = $handler;
|
|
}
|
|
|
|
public static function lookup(array $node /* = &$this->routes */, string $method, string $uri): int|array
|
|
{
|
|
$uriSegments = explode('/', trim($uri, '/'));
|
|
$params = [];
|
|
|
|
if (isset($node[$method])) return [$node[$method], $params];
|
|
|
|
if (! $node2 = array_reduce($uriSegments, function ($carry, $segment) use (&$params) {
|
|
if (isset($carry[$segment])) return $carry[$segment];
|
|
if (isset($carry[':x'])) {
|
|
$params[] = $segment;
|
|
return $carry[':x'];
|
|
}
|
|
return null;
|
|
}, $node)) return 404;
|
|
|
|
if (isset($node2[$method])) return [$node2[$method], $params];
|
|
|
|
return 405;
|
|
}
|
|
}
|