From 840b3c532022ac4a589a5dfc77340cd943fdf3df Mon Sep 17 00:00:00 2001 From: Valithor Obsidion Date: Wed, 5 Feb 2025 12:24:26 -0500 Subject: [PATCH] Abstracting lookup method --- src/SegmentRouterTrait.php | 49 +++++++++++++++++++++++++------------- 1 file changed, 32 insertions(+), 17 deletions(-) diff --git a/src/SegmentRouterTrait.php b/src/SegmentRouterTrait.php index 40162a8..081e817 100644 --- a/src/SegmentRouterTrait.php +++ b/src/SegmentRouterTrait.php @@ -63,32 +63,47 @@ trait SegmentRouterTrait // node is a reference to our current location in the node tree $node = $routes; - // if the URI is the root, and the method is defined, return the handler - if ($uri === '/' && isset($node[$method]) && array_key_exists($method, $node)) { + // if the URI is the root, and the method is defined, return the handler + if (self::isRootUri($uri, $node, $method)) { return ['code' => 200, 'handler' => $node[$method], 'params' => null]; } // params will hold any dynamic segments we find $params = []; - foreach (explode('/', trim($uri, '/')) as $segment) { - if (isset($node[$segment])) { - $node = $node[$segment]; - } elseif (isset($node[':x'])) { - $params[] = $segment; - $node = $node[':x']; - } else { - return ['code' => 404, 'handler' => null, 'params' => []]; - } + $segments = explode('/', trim($uri, '/')); + if (!self::traverseSegments($node, $segments, $params)) { + return ['code' => 404, 'handler' => null, 'params' => []]; } - // if we found a handler for the method, return it and any params. if not, return a 405 - if (array_key_exists($method, $node)) { - return ['code' => 200, 'handler' => $node[$method], 'params' => $params]; - } - - return ['code' => 405, 'handler' => null, 'params' => []]; + return self::getHandler($node, $method, $params) ?? ['code' => 405, 'handler' => null, 'params' => []]; } + private static function traverseSegments(array &$node, array $segments, array &$params): bool + { + return ($node = array_reduce($segments, function ($carry, $segment) use (&$params) { + if (isset($carry[$segment])) { + return $carry[$segment]; + } + if (isset($carry[':x'])) { + $params[] = $segment; + return $carry[':x']; + } + return false; + }, $node)) !== false; + } + + public static function isRootUri(string $uri, array &$node, string $method): bool + { + return ($uri === '/' && isset($node[$method]) && array_key_exists($method, $node)); + } + + // if we found a handler for the method, return it and any params. if not, return a 405 + public static function getHandler($node, $method, $params): ?array + { + return array_key_exists($method, $node) + ? ['code' => 200, 'handler' => $node[$method], 'params' => $params] + : null; + } /** * Clear all routes from the router. */