fix wildcard routes being skipped by fast path method lookup closes #693

Co-authored-by: Copilot <copilot@github.com>
pull/694/head
KnifeLemon 3 days ago
parent fc43882cda
commit 02fe881d27

@ -152,7 +152,7 @@ class Router
if (!isset($this->routesByMethod[$method])) { if (!isset($this->routesByMethod[$method])) {
$this->routesByMethod[$method] = []; $this->routesByMethod[$method] = [];
} }
$this->routesByMethod[$method][] = $route; $this->routesByMethod[$method][count($this->routes) - 1] = $route;
} }
return $route; return $route;
@ -270,17 +270,13 @@ class Router
} }
// Fast path: check method-specific routes first, then wildcard routes (only on first routing attempt) // Fast path: check method-specific routes first, then wildcard routes (only on first routing attempt)
$methodsToCheck = [$requestMethod, '*']; $candidates = ($this->routesByMethod[$requestMethod] ?? []) + ($this->routesByMethod['*'] ?? []);
foreach ($methodsToCheck as $method) { ksort($candidates);
if (isset($this->routesByMethod[$method])) { foreach ($candidates as $routeIndex => $route) {
foreach ($this->routesByMethod[$method] as $route) { if ($route->matchUrl($requestUrl, $this->caseSensitive)) {
if ($route->matchUrl($requestUrl, $this->caseSensitive)) { $this->executedRoute = $route;
$this->executedRoute = $route; $this->index = $routeIndex;
// Set iterator position to this route for potential next() calls return $route;
$this->index = array_search($route, $this->routes, true);
return $route;
}
}
} }
} }

@ -780,4 +780,21 @@ class RouterTest extends TestCase
$this->request->method = 'GET'; $this->request->method = 'GET';
$this->check('OK'); $this->check('OK');
} }
public function testWildcardPassthroughRouteBeforeSpecificGetRoute(): void
{
$this->router->map('/@par/[^\/]+/*', function (string $par): bool {
echo "Passthrough (Par = $par)";
return true;
});
$this->router->map('GET /[^\/]+/target', function (): void {
echo ' Target';
});
$this->request->url = '/foobar/target/';
$this->request->method = 'GET';
$this->check('Passthrough (Par = foobar) Target');
}
} }

Loading…
Cancel
Save