From 34b4e4ca20f84c32e59237be0f20aea279a510b5 Mon Sep 17 00:00:00 2001 From: Valithor Obsidion Date: Wed, 25 Dec 2024 10:38:35 -0500 Subject: [PATCH] Optimize $params using array_reduce --- src/SegmentRouter.php | 48 ++++++++++++++++++++++--------------------- 1 file changed, 25 insertions(+), 23 deletions(-) diff --git a/src/SegmentRouter.php b/src/SegmentRouter.php index a149d33..c22b63c 100644 --- a/src/SegmentRouter.php +++ b/src/SegmentRouter.php @@ -70,9 +70,6 @@ class SegmentRouter implements RouterInterface // node is a reference to our current location in the node tree $node = $this->routes; - // params will hold any dynamic segments we find - $params = []; - // if the URI is just a slash, we can return the handler for the root node if ($uri === '/') { return isset($node[$method]) @@ -80,29 +77,34 @@ class SegmentRouter implements RouterInterface : ['code' => 405, 'handler' => null, 'params' => null]; } - // 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 ['code' => 404, 'handler' => null, 'params' => []]; - } + // params will hold any dynamic segments we find + $params = array_reduce( + explode('/', trim($uri, '/')), + function ($carry, $segment) use (&$node) { + if (isset($node[$segment])) { + $node = $node[$segment]; + } elseif (isset($node[':x'])) { + $carry[] = $segment; + $node = $node[':x']; + } else { + throw new \Exception('404'); + } + return $carry; + }, + [] + ); // if we found a handler for the method, return it and any params. if not, return a 405 return isset($node[$method]) - ? ['code' => 200, 'handler' => $node[$method], 'params' => $params ?? []] - : ['code' => 405, 'handler' => null, 'params' => []]; + ? [ + 'code' => 200, + 'handler' => $node[$method], + 'params' => $params ?? []] + : [ + 'code' => 405, + 'handler' => null, + 'params' => [] + ]; } /**