dev/SegmentRouter.php
2024-09-07 13:02:52 -05:00

60 lines
1.4 KiB
PHP

<?php
class SegmentRouter
{
private array $routes = [];
public function add(string $method, string $route, callable $handler)
{
// Expand the route into segments
$segments = explode('/', trim($route, '/'));
// Push each segment into the routes array as a node
$node = &$this->routes;
foreach ($segments as $segment) $node = &$node[$segment];
// Add the handler to the last node
$node[$method] = $handler;
}
public function lookup(string $method, string $uri): int
{
// Expand the URI into segments
$uriSegments = explode('/', trim($uri, '/'));
$node = $this->routes;
$params = [];
// Traverse the routes array to find the handler
foreach ($uriSegments as $segment) {
// Check if the segment exists in the node, or if there's a dynamic segment
if (!isset($node[$segment])) {
$dynamicSegment = $this->matchDynamicSegment($node, $segment);
if ($dynamicSegment) {
$params[] = $segment;
$node = $node[$dynamicSegment];
} else {
return 404;
}
} else {
$node = $node[$segment];
}
}
// If the HTTP method is not supported, return 405
if (!isset($node[$method])) return 405;
// Call the handler
$handler = $node[$method];
call_user_func_array($handler, $params);
return 200;
}
private function matchDynamicSegment(array $node, string $segment)
{
foreach ($node as $key => $value) {
if (strpos($key, ':') === 0) return $key;
}
return null;
}
}