dev/SegmentRouter.php

71 lines
1.8 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
$node = &$this->routes;
foreach ($segments as $segment) $node = &$node[$segment];
// Add the handler to the last node
$node[$method] = $handler;
return $this;
}
public function lookup(string $method, string $uri): int|array
{
// 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
if (isset($node[$segment])) {
$node = $node[$segment];
} else {
// Handle dynamic segments (starting with ":")
$dynamicSegment = null;
// Loop through the node and find the first dynamic segment
foreach ($node as $k => $v) {
if (str_starts_with($k, ':')) {
$dynamicSegment = $k;
break; // Break early as we only need one match
}
}
// If no dynamic segment was found, return 404
if ($dynamicSegment === null) return 404;
// Otherwise, store the parameter and move to the dynamic node
$params[] = $segment;
$node = $node[$dynamicSegment];
}
}
// Check if the HTTP method is supported
if (!isset($node[$method])) return 405;
// Return the handler and parameters
return [$node[$method] , $params];
}
public function clear(): Router
{
$this->routes = [];
return $this;
}
}