From 90b8049dc4c50f5b7e3526510ea1fb7827281691 Mon Sep 17 00:00:00 2001 From: Sky Johnson Date: Wed, 11 Sep 2024 12:16:36 -0500 Subject: [PATCH] Add comments and clean up some conditionals for segment --- SegmentRouter.php | 30 ++++++++++++++++++++++-------- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/SegmentRouter.php b/SegmentRouter.php index d5bf9d4..2ff0863 100644 --- a/SegmentRouter.php +++ b/SegmentRouter.php @@ -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]; }