Abstracting lookup method

This commit is contained in:
Valithor Obsidion 2025-02-05 12:24:26 -05:00
parent 9fdef6b250
commit 840b3c5320

View File

@ -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.
*/