66 lines
1.3 KiB
PHP
66 lines
1.3 KiB
PHP
<?php
|
|
|
|
class SegmentRouter implements Router
|
|
{
|
|
public array $routes = [];
|
|
|
|
public function add(string $method, string $route, callable $handler): Router
|
|
{
|
|
// Expand the route into segments and make dynamic segments into a common placeholder
|
|
$segments = array_map(function($segment) {
|
|
return str_starts_with($segment, ':') ? ':x' : $segment;
|
|
}, explode('/', trim($route, '/')));
|
|
|
|
// Push each segment into the routes array as a node, except if this is the root node
|
|
$node = &$this->routes;
|
|
foreach ($segments as $segment) {
|
|
if ($segment === '') continue;
|
|
$node = &$node[$segment];
|
|
}
|
|
|
|
// Add the handler to the last node
|
|
$node[$method] = $handler;
|
|
|
|
return $this;
|
|
}
|
|
|
|
public function lookup(string $method, string $uri): int|array
|
|
{
|
|
$node = $this->routes;
|
|
|
|
if (isset($node[$uri])) {
|
|
if (isset($node[$uri][$method])) return [$node[$uri][$method], []];
|
|
return 405;
|
|
}
|
|
|
|
$uriSegments = explode('/', trim($uri, '/'));
|
|
$params = [];
|
|
|
|
foreach ($uriSegments as $segment) {
|
|
if (isset($node[$segment])) {
|
|
$node = $node[$segment];
|
|
continue;
|
|
}
|
|
|
|
if (isset($node[':x'])) {
|
|
$params[] = $segment;
|
|
$node = $node[':x'];
|
|
continue;
|
|
}
|
|
|
|
return 404;
|
|
}
|
|
|
|
if (!isset($node[$method])) return 405;
|
|
|
|
return [$node[$method], $params];
|
|
}
|
|
|
|
|
|
public function clear(): Router
|
|
{
|
|
$this->routes = [];
|
|
return $this;
|
|
}
|
|
}
|