Router/SegmentRouter.php

66 lines
1.3 KiB
PHP
Raw Normal View History

2024-09-07 13:02:52 -05:00
<?php
class SegmentRouter implements Router
2024-09-07 13:02:52 -05:00
{
public array $routes = [];
2024-09-07 13:02:52 -05:00
public function add(string $method, string $route, callable $handler): Router
2024-09-07 13:02:52 -05:00
{
// 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, '/')));
2024-09-07 13:02:52 -05:00
// Push each segment into the routes array as a node, except if this is the root node
2024-09-07 13:02:52 -05:00
$node = &$this->routes;
foreach ($segments as $segment) {
if ($segment === '') continue;
$node = &$node[$segment];
}
2024-09-07 13:02:52 -05:00
// Add the handler to the last node
$node[$method] = $handler;
return $this;
2024-09-07 13:02:52 -05:00
}
public function lookup(string $method, string $uri): int|array
2024-09-07 13:02:52 -05:00
{
$node = $this->routes;
if (isset($node[$uri])) {
if (isset($node[$uri][$method])) return [$node[$uri][$method], []];
return 405;
}
$uriSegments = explode('/', trim($uri, '/'));
2024-09-07 13:02:52 -05:00
$params = [];
2024-09-07 13:02:52 -05:00
foreach ($uriSegments as $segment) {
if (isset($node[$segment])) {
2024-09-07 13:02:52 -05:00
$node = $node[$segment];
continue;
}
if (isset($node[':x'])) {
$params[] = $segment;
$node = $node[':x'];
continue;
2024-09-07 13:02:52 -05:00
}
return 404;
2024-09-07 13:02:52 -05:00
}
2024-09-07 13:02:52 -05:00
if (!isset($node[$method])) return 405;
return [$node[$method], $params];
}
public function clear(): Router
{
$this->routes = [];
return $this;
2024-09-07 13:02:52 -05:00
}
}