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
{
// normalize uri to be tolerant of trailing slashes
$uri = '/' . trim($uri, '/');
// trim once and reuse
$trimmed = trim($uri, '/');
// node is a reference to our current location in the node tree
$node = $this->routes;
@ -52,8 +52,8 @@ class Router
// init the response array
$res = ['code' => 0, 'handler' => null, 'params' => []];
// if the URI is just a slash, we can return the handler for the root node
if ($uri === '/') {
// if the URI is root
if ($trimmed === '') {
if (!$this->checkForHandlers($node)) {
$res['code'] = 404;
return $res;
@ -70,7 +70,7 @@ class Router
}
// 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
if (isset($node[$segment]) && is_array($node[$segment])) {
$node = $node[$segment];