Skip to content

Commit 893f1e1

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 893f1e1

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,109 +450,123 @@ 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+
// `#` is the pattern delimiter used below, so it must be treated as a metacharacter.
454+
$isRegex = strpbrk($routeKey, '()[]?*+{}^$\\.|#') !== false;
457455

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-
);
456+
if (! $isRegex) {
457+
if ($routeKey !== $uri) {
458+
continue;
473459
}
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-
}
489460

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

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;
468+
// Does the RegEx match?
469+
if (! preg_match('#^' . $routeKey . '$#u', $uri, $matches)) {
470+
continue;
471+
}
472+
}
499473

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

503-
$this->params = $matches;
480+
return '$' . $i++;
481+
}, is_array($handler) ? key($handler) : $handler);
504482

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

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

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

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

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

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-
}
555+
$segments = [];
556+
557+
foreach ($handlerSegments as $segment) {
558+
$segments[] = $this->replaceBackReferences($segment, $matches);
545559
}
546-
} else {
547-
$segments = explode('/', $handler);
548560
}
561+
} else {
562+
$segments = explode('/', $handler);
563+
}
549564

550-
$this->setRequest($segments);
565+
$this->setRequest($segments);
551566

552-
$this->setMatchedRoute($matchedKey, $handler);
567+
$this->setMatchedRoute($matchedKey, $handler);
553568

554-
return true;
555-
}
569+
return true;
556570
}
557571

558572
return false;

‎tests/system/Router/RouterTest.php‎

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1031,4 +1031,105 @@ 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+
}
1089+
1090+
public function testRouteWithUnescapedHashIsNotMatchedAsStaticRoute(): void
1091+
{
1092+
config(App::class)->permittedURIChars = 'a-z 0-9~%.:_\-#';
1093+
1094+
$collection = clone $this->collection;
1095+
$collection->resetRoutes();
1096+
$collection->get('docs#anchor', 'Docs::anchor');
1097+
1098+
$router = new Router($collection, $this->request);
1099+
1100+
// `#` is the PCRE delimiter, so the key must go through the regex branch
1101+
// instead of a plain string comparison. The unescaped delimiter makes
1102+
// the pattern invalid, so the route can't match.
1103+
$warnings = [];
1104+
set_error_handler(static function (int $errno, string $errstr) use (&$warnings): bool {
1105+
$warnings[] = $errstr;
1106+
1107+
return true;
1108+
}, E_WARNING);
1109+
1110+
try {
1111+
$router->handle('docs#anchor');
1112+
$this->fail('PageNotFoundException was expected.');
1113+
} catch (PageNotFoundException) {
1114+
$this->assertCount(1, $warnings);
1115+
$this->assertStringContainsString('preg_match()', $warnings[0]);
1116+
} finally {
1117+
restore_error_handler();
1118+
}
1119+
}
1120+
1121+
public function testRouteWithEscapedHashMatchesViaRegexBranch(): void
1122+
{
1123+
config(App::class)->permittedURIChars = 'a-z 0-9~%.:_\-#';
1124+
1125+
$collection = clone $this->collection;
1126+
$collection->resetRoutes();
1127+
$collection->get('docs\#anchor', 'Docs::anchor');
1128+
1129+
$router = new Router($collection, $this->request);
1130+
$router->handle('docs#anchor');
1131+
1132+
$this->assertSame('\Docs', $router->controllerName());
1133+
$this->assertSame('anchor', $router->methodName());
1134+
}
10341135
}

0 commit comments

Comments
 (0)