Skip to content

Commit 472ee9f

Browse files
committed
perf: add fast-path for static routes in Router::checkRoutes()
Avoid executing PCRE for static routes by checking for PCRE metacharacters (including pattern delimiter '#') using strpbrk(). If none are present, perform a direct string comparison against the request URI. This reduces matching overhead from O(N) PCRE invocations to O(1) string checks for static routes while strictly preserving registration precedence and existing handler, Closure, redirect, and locale behavior.
1 parent 27a1e6a commit 472ee9f

2 files changed

Lines changed: 153 additions & 82 deletions

File tree

‎system/Router/Router.php‎

Lines changed: 98 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -450,109 +450,125 @@ protected function checkRoutes(string $uri): bool
450450

451451
$matchedKey = $routeKey;
452452

453-
// Are we dealing with a locale?
454-
if (str_contains($routeKey, '{locale}')) {
455-
$routeKey = str_replace('{locale}', '[^/]+', $routeKey);
456-
}
453+
// Route keys without PCRE metacharacters (including the pattern
454+
// delimiter `#`) can be compared as plain strings, avoiding a
455+
// PCRE call for static routes.
456+
$isRegex = strpbrk($routeKey, '()[]?*+{}^$\\.|#') !== false;
457457

458-
// Does the RegEx match?
459-
if (preg_match('#^' . $routeKey . '$#u', $uri, $matches)) {
460-
// Is this route supposed to redirect to another?
461-
if ($this->collection->isRedirect($routeKey)) {
462-
// replacing matched route groups with references: post/([0-9]+) -> post/$1
463-
$redirectTo = preg_replace_callback('/(\([^\(]+\))/', static function (): string {
464-
static $i = 1;
465-
466-
return '$' . $i++;
467-
}, is_array($handler) ? key($handler) : $handler);
468-
469-
throw new RedirectException(
470-
preg_replace('#\A' . $routeKey . '\z#u', $redirectTo, $uri),
471-
$this->collection->getRedirectCode($routeKey),
472-
);
458+
if (! $isRegex) {
459+
if ($routeKey !== $uri) {
460+
continue;
473461
}
474-
// Store our locale so CodeIgniter object can
475-
// assign it to the Request.
476-
if (str_contains($matchedKey, '{locale}')) {
477-
preg_match(
478-
'#^' . str_replace('{locale}', '(?<locale>[^/]+)', $matchedKey) . '$#u',
479-
$uri,
480-
$matched,
481-
);
482-
483-
if ($this->collection->shouldUseSupportedLocalesOnly()
484-
&& ! in_array($matched['locale'], config(App::class)->supportedLocales, true)) {
485-
// Throw exception to prevent the autorouter, if enabled,
486-
// from trying to find a route
487-
throw PageNotFoundException::forLocaleNotSupported($matched['locale']);
488-
}
489462

490-
$this->detectedLocale = $matched['locale'];
491-
unset($matched);
463+
$matches = [$uri];
464+
} else {
465+
// Are we dealing with a locale?
466+
if (str_contains($routeKey, '{locale}')) {
467+
$routeKey = str_replace('{locale}', '[^/]+', $routeKey);
492468
}
493469

494-
// Are we using Closures? If so, then we need
495-
// to collect the params into an array
496-
// so it can be passed to the controller method later.
497-
if (! is_string($handler) && is_callable($handler)) {
498-
$this->controller = $handler;
470+
// Does the RegEx match?
471+
if (! preg_match('#^' . $routeKey . '$#u', $uri, $matches)) {
472+
continue;
473+
}
474+
}
499475

500-
// Remove the original string from the matches array
501-
array_shift($matches);
476+
// Is this route supposed to redirect to another?
477+
if ($this->collection->isRedirect($routeKey)) {
478+
// replacing matched route groups with references: post/([0-9]+) -> post/$1
479+
$redirectTo = preg_replace_callback('/(\([^\(]+\))/', static function (): string {
480+
static $i = 1;
502481

503-
$this->params = $matches;
482+
return '$' . $i++;
483+
}, is_array($handler) ? key($handler) : $handler);
504484

505-
$this->setMatchedRoute($matchedKey, $handler);
485+
throw new RedirectException(
486+
preg_replace('#\A' . $routeKey . '\z#u', $redirectTo, $uri),
487+
$this->collection->getRedirectCode($routeKey),
488+
);
489+
}
506490

507-
return true;
508-
}
491+
// Store our locale so CodeIgniter object can
492+
// assign it to the Request.
493+
if (str_contains($matchedKey, '{locale}')) {
494+
preg_match(
495+
'#^' . str_replace('{locale}', '(?<locale>[^/]+)', $matchedKey) . '$#u',
496+
$uri,
497+
$matched,
498+
);
509499

510-
if (str_contains($handler, '::')) {
511-
[$controller, $methodAndParams] = explode('::', $handler);
512-
} else {
513-
$controller = $handler;
514-
$methodAndParams = '';
500+
if ($this->collection->shouldUseSupportedLocalesOnly()
501+
&& ! in_array($matched['locale'], config(App::class)->supportedLocales, true)) {
502+
// Throw exception to prevent the autorouter, if enabled,
503+
// from trying to find a route
504+
throw PageNotFoundException::forLocaleNotSupported($matched['locale']);
515505
}
516506

517-
// Checks `/` in controller name
518-
if (str_contains($controller, '/')) {
519-
throw RouterException::forInvalidControllerName($handler);
507+
$this->detectedLocale = $matched['locale'];
508+
unset($matched);
509+
}
510+
511+
// Are we using Closures? If so, then we need
512+
// to collect the params into an array
513+
// so it can be passed to the controller method later.
514+
if (! is_string($handler) && is_callable($handler)) {
515+
$this->controller = $handler;
516+
517+
// Remove the original string from the matches array
518+
array_shift($matches);
519+
520+
$this->params = $matches;
521+
522+
$this->setMatchedRoute($matchedKey, $handler);
523+
524+
return true;
525+
}
526+
527+
if (str_contains($handler, '::')) {
528+
[$controller, $methodAndParams] = explode('::', $handler);
529+
} else {
530+
$controller = $handler;
531+
$methodAndParams = '';
532+
}
533+
534+
// Checks `/` in controller name
535+
if (str_contains($controller, '/')) {
536+
throw RouterException::forInvalidControllerName($handler);
537+
}
538+
539+
if (str_contains($handler, '$') && str_contains($routeKey, '(')) {
540+
// Checks dynamic controller
541+
if (str_contains($controller, '$')) {
542+
throw RouterException::forDynamicController($handler);
520543
}
521544

522-
if (str_contains($handler, '$') && str_contains($routeKey, '(')) {
523-
// Checks dynamic controller
524-
if (str_contains($controller, '$')) {
525-
throw RouterException::forDynamicController($handler);
545+
if (config(Routing::class)->multipleSegmentsOneParam === false) {
546+
// Using back-references
547+
$segments = explode('/', preg_replace('#\A' . $routeKey . '\z#u', $handler, $uri));
548+
} else {
549+
if (str_contains($methodAndParams, '/')) {
550+
[$method, $handlerParams] = explode('/', $methodAndParams, 2);
551+
$params = explode('/', $handlerParams);
552+
$handlerSegments = array_merge([$controller . '::' . $method], $params);
553+
} else {
554+
$handlerSegments = [$handler];
526555
}
527556

528-
if (config(Routing::class)->multipleSegmentsOneParam === false) {
529-
// Using back-references
530-
$segments = explode('/', preg_replace('#\A' . $routeKey . '\z#u', $handler, $uri));
531-
} else {
532-
if (str_contains($methodAndParams, '/')) {
533-
[$method, $handlerParams] = explode('/', $methodAndParams, 2);
534-
$params = explode('/', $handlerParams);
535-
$handlerSegments = array_merge([$controller . '::' . $method], $params);
536-
} else {
537-
$handlerSegments = [$handler];
538-
}
539-
540-
$segments = [];
541-
542-
foreach ($handlerSegments as $segment) {
543-
$segments[] = $this->replaceBackReferences($segment, $matches);
544-
}
557+
$segments = [];
558+
559+
foreach ($handlerSegments as $segment) {
560+
$segments[] = $this->replaceBackReferences($segment, $matches);
545561
}
546-
} else {
547-
$segments = explode('/', $handler);
548562
}
563+
} else {
564+
$segments = explode('/', $handler);
565+
}
549566

550-
$this->setRequest($segments);
567+
$this->setRequest($segments);
551568

552-
$this->setMatchedRoute($matchedKey, $handler);
569+
$this->setMatchedRoute($matchedKey, $handler);
553570

554-
return true;
555-
}
571+
return true;
556572
}
557573

558574
return false;

‎tests/system/Router/RouterTest.php‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1031,4 +1031,59 @@ public function testLogsRouteAttributeInstantiationFailureWithContext(): void
10311031
$this->assertLogContains('error', 'Failed to instantiate route attribute "' . Filter::class . '" on "\Tests\Support\Router\Controllers\InvalidAttributeController::invalidMultipleFilters()":');
10321032
$this->assertLogContains('error', 'must be of type string');
10331033
}
1034+
1035+
public function testStaticRoutesMatchControllerClosureAndNumericKey(): void
1036+
{
1037+
$collection = clone $this->collection;
1038+
$collection->resetRoutes();
1039+
$collection->get('about-us', 'Home::about');
1040+
$collection->get('contact_page', static fn (): string => 'contact-page-content');
1041+
$collection->get('123', 'Home::numericRoute');
1042+
1043+
$router = new Router($collection, $this->request);
1044+
1045+
$router->handle('about-us');
1046+
$this->assertSame('\Home', $router->controllerName());
1047+
$this->assertSame('about', $router->methodName());
1048+
$this->assertSame([], $router->params());
1049+
1050+
$router->handle('contact_page');
1051+
$controller = $router->controllerName();
1052+
$this->assertInstanceOf(Closure::class, $controller);
1053+
$this->assertSame('contact-page-content', $controller());
1054+
$this->assertSame([], $router->params());
1055+
1056+
$router->handle('123');
1057+
$this->assertSame('\Home', $router->controllerName());
1058+
$this->assertSame('numericRoute', $router->methodName());
1059+
$this->assertSame([], $router->params());
1060+
}
1061+
1062+
public function testStaticRouteDoesNotMatchAdditionalSegments(): void
1063+
{
1064+
$collection = clone $this->collection;
1065+
$collection->resetRoutes();
1066+
$collection->get('about-us', 'Home::about');
1067+
1068+
$router = new Router($collection, $this->request);
1069+
1070+
$this->expectException(PageNotFoundException::class);
1071+
1072+
$router->handle('about-us/team');
1073+
}
1074+
1075+
public function testEarlierDynamicRouteTakesPrecedenceOverLaterStaticRoute(): void
1076+
{
1077+
$collection = clone $this->collection;
1078+
$collection->resetRoutes();
1079+
$collection->get('items/(:segment)', 'Items::detail/$1');
1080+
$collection->get('items/new', 'Items::new');
1081+
1082+
$router = new Router($collection, $this->request);
1083+
$router->handle('items/new');
1084+
1085+
$this->assertSame('\Items', $router->controllerName());
1086+
$this->assertSame('detail', $router->methodName());
1087+
$this->assertSame(['new'], $router->params());
1088+
}
10341089
}

0 commit comments

Comments
 (0)