Optimize $params using array_reduce

This commit is contained in:
Valithor Obsidion 2024-12-25 10:38:35 -05:00
parent 4f5f2599f5
commit 34b4e4ca20

View File

@ -70,9 +70,6 @@ class SegmentRouter implements RouterInterface
// node is a reference to our current location in the node tree // node is a reference to our current location in the node tree
$node = $this->routes; $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 the URI is just a slash, we can return the handler for the root node
if ($uri === '/') { if ($uri === '/') {
return isset($node[$method]) return isset($node[$method])
@ -80,29 +77,34 @@ class SegmentRouter implements RouterInterface
: ['code' => 405, 'handler' => null, 'params' => null]; : ['code' => 405, 'handler' => null, 'params' => null];
} }
// We'll split up the URI into segments and traverse the node tree // params will hold any dynamic segments we find
foreach (explode('/', trim($uri, '/')) as $segment) { $params = array_reduce(
// if there is a node for this segment, move to it explode('/', trim($uri, '/')),
if (isset($node[$segment])) { function ($carry, $segment) use (&$node) {
$node = $node[$segment]; if (isset($node[$segment])) {
continue; $node = $node[$segment];
} } elseif (isset($node[':x'])) {
$carry[] = $segment;
// if there is a dynamic segment, move to it and store the value $node = $node[':x'];
if (isset($node[':x'])) { } else {
$params[] = $segment; throw new \Exception('404');
$node = $node[':x']; }
continue; return $carry;
} },
[]
// if we can't find a node for this segment, return 404 );
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 we found a handler for the method, return it and any params. if not, return a 405
return isset($node[$method]) 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' => []
];
} }
/** /**