minimize trim ops in lookup

This commit is contained in:
Sky Johnson 2025-09-20 10:42:13 -05:00
parent 41e151f031
commit 35299c9632

View File

@ -43,8 +43,8 @@ class Router
*/ */
public function lookup(string $method, string $uri): array public function lookup(string $method, string $uri): array
{ {
// normalize uri to be tolerant of trailing slashes // trim once and reuse
$uri = '/' . trim($uri, '/'); $trimmed = trim($uri, '/');
// 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;
@ -52,8 +52,8 @@ class Router
// init the response array // init the response array
$res = ['code' => 0, 'handler' => null, 'params' => []]; $res = ['code' => 0, 'handler' => null, 'params' => []];
// if the URI is just a slash, we can return the handler for the root node // if the URI is root
if ($uri === '/') { if ($trimmed === '') {
if (!$this->checkForHandlers($node)) { if (!$this->checkForHandlers($node)) {
$res['code'] = 404; $res['code'] = 404;
return $res; return $res;
@ -70,7 +70,7 @@ class Router
} }
// we'll split up the URI into segments and traverse the node tree // we'll split up the URI into segments and traverse the node tree
foreach (explode('/', trim($uri, '/')) as $segment) { foreach (explode('/', $trimmed) as $segment) {
// check that the next segment is an array (not a callable) and exists, then move to it // check that the next segment is an array (not a callable) and exists, then move to it
if (isset($node[$segment]) && is_array($node[$segment])) { if (isset($node[$segment]) && is_array($node[$segment])) {
$node = $node[$segment]; $node = $node[$segment];