Skip to content

Commit aab92a1

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 ae19ffd commit aab92a1

2 files changed

Lines changed: 197 additions & 82 deletions

File tree

‎system/Router/Router.php‎

Lines changed: 96 additions & 82 deletions
Original file line numberDiff line numberDiff line change
@@ -450,113 +450,127 @@ 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);
453+
// `#` is the pattern delimiter used below, so it must be treated as a metacharacter.
454+
$isRegex = strpbrk($routeKey, '()[]?*+{}^$\\.|#') !== false;
455+
456+
if (! $isRegex) {
457+
if ($routeKey !== $uri) {
458+
continue;
459+
}
460+
461+
$matches = [$uri];
462+
} else {
463+
// Are we dealing with a locale?
464+
if (str_contains($routeKey, '{locale}')) {
465+
$routeKey = str_replace('{locale}', '[^/]+', $routeKey);
466+
}
467+
468+
// Does the RegEx match?
469+
if (! preg_match('#^' . $routeKey . '$#u', $uri, $matches)) {
470+
continue;
471+
}
456472
}
457473

458-
// Does the RegEx match?
459-
if (preg_match('#^' . $routeKey . '$#u', $uri, $matches)) {
460-
// Store our locale so CodeIgniter object can
461-
// assign it to the Request.
462-
if (str_contains($matchedKey, '{locale}')) {
463-
preg_match(
464-
'#^' . str_replace('{locale}', '(?<locale>[^/]+)', $matchedKey) . '$#u',
465-
$uri,
466-
$matched,
467-
);
468-
469-
if ($this->collection->shouldUseSupportedLocalesOnly()
470-
&& ! in_array($matched['locale'], config(App::class)->supportedLocales, true)) {
471-
// Throw exception to prevent the autorouter, if enabled,
472-
// from trying to find a route
473-
throw PageNotFoundException::forLocaleNotSupported($matched['locale']);
474-
}
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+
);
475482

476-
$this->detectedLocale = $matched['locale'];
477-
unset($matched);
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']);
478488
}
479489

480-
if ($this->collection->isRedirect($matchedKey)) {
481-
// replacing matched route groups with references: post/([0-9]+) -> post/$1
482-
$redirectTo = preg_replace_callback('/(\([^\(]+\))/', static function (): string {
483-
static $i = 1;
490+
$this->detectedLocale = $matched['locale'];
491+
unset($matched);
492+
}
484493

485-
return '$' . $i++;
486-
}, is_array($handler) ? key($handler) : $handler);
494+
// Is this route supposed to redirect to another?
495+
if ($this->collection->isRedirect($matchedKey)) {
496+
// replacing matched route groups with references: post/([0-9]+) -> post/$1
497+
$redirectTo = preg_replace_callback('/(\([^\(]+\))/', static function (): string {
498+
static $i = 1;
487499

488-
if (str_contains($matchedKey, '{locale}')) {
489-
$redirectTo = str_replace('{locale}', $this->detectedLocale, $redirectTo);
490-
}
500+
return '$' . $i++;
501+
}, is_array($handler) ? key($handler) : $handler);
491502

492-
throw new RedirectException(
493-
preg_replace('#\A' . $routeKey . '\z#u', $redirectTo, $uri),
494-
$this->collection->getRedirectCode($matchedKey),
495-
);
503+
if (str_contains($matchedKey, '{locale}')) {
504+
$redirectTo = str_replace('{locale}', $this->detectedLocale, $redirectTo);
496505
}
497506

498-
// Are we using Closures? If so, then we need
499-
// to collect the params into an array
500-
// so it can be passed to the controller method later.
501-
if (! is_string($handler) && is_callable($handler)) {
502-
$this->controller = $handler;
507+
throw new RedirectException(
508+
preg_replace('#\A' . $routeKey . '\z#u', $redirectTo, $uri),
509+
$this->collection->getRedirectCode($matchedKey),
510+
);
511+
}
503512

504-
// Remove the original string from the matches array
505-
array_shift($matches);
513+
// Are we using Closures? If so, then we need
514+
// to collect the params into an array
515+
// so it can be passed to the controller method later.
516+
if (! is_string($handler) && is_callable($handler)) {
517+
$this->controller = $handler;
506518

507-
$this->params = $matches;
519+
// Remove the original string from the matches array
520+
array_shift($matches);
508521

509-
$this->setMatchedRoute($matchedKey, $handler);
522+
$this->params = $matches;
510523

511-
return true;
512-
}
524+
$this->setMatchedRoute($matchedKey, $handler);
513525

514-
if (str_contains($handler, '::')) {
515-
[$controller, $methodAndParams] = explode('::', $handler);
516-
} else {
517-
$controller = $handler;
518-
$methodAndParams = '';
519-
}
526+
return true;
527+
}
528+
529+
if (str_contains($handler, '::')) {
530+
[$controller, $methodAndParams] = explode('::', $handler);
531+
} else {
532+
$controller = $handler;
533+
$methodAndParams = '';
534+
}
520535

521-
// Checks `/` in controller name
522-
if (str_contains($controller, '/')) {
523-
throw RouterException::forInvalidControllerName($handler);
536+
// Checks `/` in controller name
537+
if (str_contains($controller, '/')) {
538+
throw RouterException::forInvalidControllerName($handler);
539+
}
540+
541+
if (str_contains($handler, '$') && str_contains($routeKey, '(')) {
542+
// Checks dynamic controller
543+
if (str_contains($controller, '$')) {
544+
throw RouterException::forDynamicController($handler);
524545
}
525546

526-
if (str_contains($handler, '$') && str_contains($routeKey, '(')) {
527-
// Checks dynamic controller
528-
if (str_contains($controller, '$')) {
529-
throw RouterException::forDynamicController($handler);
547+
if (config(Routing::class)->multipleSegmentsOneParam === false) {
548+
// Using back-references
549+
$segments = explode('/', preg_replace('#\A' . $routeKey . '\z#u', $handler, $uri));
550+
} else {
551+
if (str_contains($methodAndParams, '/')) {
552+
[$method, $handlerParams] = explode('/', $methodAndParams, 2);
553+
$params = explode('/', $handlerParams);
554+
$handlerSegments = array_merge([$controller . '::' . $method], $params);
555+
} else {
556+
$handlerSegments = [$handler];
530557
}
531558

532-
if (config(Routing::class)->multipleSegmentsOneParam === false) {
533-
// Using back-references
534-
$segments = explode('/', preg_replace('#\A' . $routeKey . '\z#u', $handler, $uri));
535-
} else {
536-
if (str_contains($methodAndParams, '/')) {
537-
[$method, $handlerParams] = explode('/', $methodAndParams, 2);
538-
$params = explode('/', $handlerParams);
539-
$handlerSegments = array_merge([$controller . '::' . $method], $params);
540-
} else {
541-
$handlerSegments = [$handler];
542-
}
543-
544-
$segments = [];
545-
546-
foreach ($handlerSegments as $segment) {
547-
$segments[] = $this->replaceBackReferences($segment, $matches);
548-
}
559+
$segments = [];
560+
561+
foreach ($handlerSegments as $segment) {
562+
$segments[] = $this->replaceBackReferences($segment, $matches);
549563
}
550-
} else {
551-
$segments = explode('/', $handler);
552564
}
565+
} else {
566+
$segments = explode('/', $handler);
567+
}
553568

554-
$this->setRequest($segments);
569+
$this->setRequest($segments);
555570

556-
$this->setMatchedRoute($matchedKey, $handler);
571+
$this->setMatchedRoute($matchedKey, $handler);
557572

558-
return true;
559-
}
573+
return true;
560574
}
561575

562576
return false;

‎tests/system/Router/RouterTest.php‎

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1057,4 +1057,105 @@ public function testLogsRouteAttributeInstantiationFailureWithContext(): void
10571057
$this->assertLogContains('error', 'Failed to instantiate route attribute "' . Filter::class . '" on "\Tests\Support\Router\Controllers\InvalidAttributeController::invalidMultipleFilters()":');
10581058
$this->assertLogContains('error', 'must be of type string');
10591059
}
1060+
1061+
public function testStaticRoutesMatchControllerClosureAndNumericKey(): void
1062+
{
1063+
$collection = clone $this->collection;
1064+
$collection->resetRoutes();
1065+
$collection->get('about-us', 'Home::about');
1066+
$collection->get('contact_page', static fn (): string => 'contact-page-content');
1067+
$collection->get('123', 'Home::numericRoute');
1068+
1069+
$router = new Router($collection, $this->request);
1070+
1071+
$router->handle('about-us');
1072+
$this->assertSame('\Home', $router->controllerName());
1073+
$this->assertSame('about', $router->methodName());
1074+
$this->assertSame([], $router->params());
1075+
1076+
$router->handle('contact_page');
1077+
$controller = $router->controllerName();
1078+
$this->assertInstanceOf(Closure::class, $controller);
1079+
$this->assertSame('contact-page-content', $controller());
1080+
$this->assertSame([], $router->params());
1081+
1082+
$router->handle('123');
1083+
$this->assertSame('\Home', $router->controllerName());
1084+
$this->assertSame('numericRoute', $router->methodName());
1085+
$this->assertSame([], $router->params());
1086+
}
1087+
1088+
public function testStaticRouteDoesNotMatchAdditionalSegments(): void
1089+
{
1090+
$collection = clone $this->collection;
1091+
$collection->resetRoutes();
1092+
$collection->get('about-us', 'Home::about');
1093+
1094+
$router = new Router($collection, $this->request);
1095+
1096+
$this->expectException(PageNotFoundException::class);
1097+
1098+
$router->handle('about-us/team');
1099+
}
1100+
1101+
public function testEarlierDynamicRouteTakesPrecedenceOverLaterStaticRoute(): void
1102+
{
1103+
$collection = clone $this->collection;
1104+
$collection->resetRoutes();
1105+
$collection->get('items/(:segment)', 'Items::detail/$1');
1106+
$collection->get('items/new', 'Items::new');
1107+
1108+
$router = new Router($collection, $this->request);
1109+
$router->handle('items/new');
1110+
1111+
$this->assertSame('\Items', $router->controllerName());
1112+
$this->assertSame('detail', $router->methodName());
1113+
$this->assertSame(['new'], $router->params());
1114+
}
1115+
1116+
public function testRouteWithUnescapedHashIsNotMatchedAsStaticRoute(): void
1117+
{
1118+
config(App::class)->permittedURIChars = 'a-z 0-9~%.:_\-#';
1119+
1120+
$collection = clone $this->collection;
1121+
$collection->resetRoutes();
1122+
$collection->get('docs#anchor', 'Docs::anchor');
1123+
1124+
$router = new Router($collection, $this->request);
1125+
1126+
// `#` is the PCRE delimiter, so the key must go through the regex branch
1127+
// instead of a plain string comparison. The unescaped delimiter makes
1128+
// the pattern invalid, so the route can't match.
1129+
$warnings = [];
1130+
set_error_handler(static function (int $errno, string $errstr) use (&$warnings): bool {
1131+
$warnings[] = $errstr;
1132+
1133+
return true;
1134+
}, E_WARNING);
1135+
1136+
try {
1137+
$router->handle('docs#anchor');
1138+
$this->fail('PageNotFoundException was expected.');
1139+
} catch (PageNotFoundException) {
1140+
$this->assertCount(1, $warnings);
1141+
$this->assertStringContainsString('preg_match()', $warnings[0]);
1142+
} finally {
1143+
restore_error_handler();
1144+
}
1145+
}
1146+
1147+
public function testRouteWithEscapedHashMatchesViaRegexBranch(): void
1148+
{
1149+
config(App::class)->permittedURIChars = 'a-z 0-9~%.:_\-#';
1150+
1151+
$collection = clone $this->collection;
1152+
$collection->resetRoutes();
1153+
$collection->get('docs\#anchor', 'Docs::anchor');
1154+
1155+
$router = new Router($collection, $this->request);
1156+
$router->handle('docs#anchor');
1157+
1158+
$this->assertSame('\Docs', $router->controllerName());
1159+
$this->assertSame('anchor', $router->methodName());
1160+
}
10601161
}

0 commit comments

Comments
 (0)