Add comments and clean up some conditionals for segment

This commit is contained in:
Sky Johnson 2024-09-11 12:16:36 -05:00
parent 290fc105e9
commit 90b8049dc4

View File

@ -4,6 +4,10 @@ class SegmentRouter implements Router
{
public array $routes = [];
/**
* Add a route to the router. The route can contain dynamic segments, which are denoted by a colon. They are
* inserted into the node tree per segment; if a segment is dynamic, it is stored under the key ':x'.
*/
public function add(string $method, string $route, callable $handler): Router
{
// Expand the route into segments and make dynamic segments into a common placeholder
@ -14,8 +18,9 @@ class SegmentRouter implements Router
// Push each segment into the routes array as a node, except if this is the root node
$node = &$this->routes;
foreach ($segments as $segment) {
// skip an empty segment, which allows us to register handlers for the root node
if ($segment === '') continue;
$node = &$node[$segment];
$node = &$node[$segment]; // build the node tree as we go
}
// Add the handler to the last node
@ -24,35 +29,44 @@ class SegmentRouter implements Router
return $this;
}
/**
* Lookup a route in the router. This method will return the handler for the route if it is found, or a 404 or 405
* status code if the route is not found or the method is not allowed. If the route contains dynamic segments, the
* method will return an array with the handler and the dynamic segments.
*
* @return [callable, array] | int
*/
public function lookup(string $method, string $uri): int|array
{
// node is a reference to our current location in the node tree
$node = $this->routes;
if (isset($node[$uri])) {
if (isset($node[$uri][$method])) return [$node[$uri][$method], []];
return 405;
}
$uriSegments = explode('/', trim($uri, '/'));
// params will hold any dynamic segments we find
$params = [];
foreach ($uriSegments as $segment) {
// We'll split up the URI into segments and traverse the node tree
foreach (explode('/', trim($uri, '/')) as $segment) {
// if there is a node for this segment, move to it
if (isset($node[$segment])) {
$node = $node[$segment];
continue;
}
// if there is a dynamic segment, move to it and store the value
if (isset($node[':x'])) {
$params[] = $segment;
$node = $node[':x'];
continue;
}
// if we can't find a node for this segment, return 404
return 404;
}
// if we fail to find a handler for the method, return 405
if (!isset($node[$method])) return 405;
// return the handler and any dynamic segments we found
return [$node[$method], $params];
}