Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Persist routes indexed by name in RouteCollector for improved performance. #3235

Merged
merged 6 commits into from
Nov 6, 2022
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 18 additions & 5 deletions Slim/Routing/RouteCollector.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,13 @@ class RouteCollector implements RouteCollectorInterface
*/
protected array $routes = [];

/**
* Routes indexed by name
*
* @var RouteInterface[]
*/
protected array $routesByName = [];

/**
* Route groups
*
Expand Down Expand Up @@ -172,7 +179,8 @@ public function getRoutes(): array
public function removeNamedRoute(string $name): RouteCollectorInterface
{
$route = $this->getNamedRoute($name);
unset($this->routes[$route->getIdentifier()]);

unset($this->routesByName[$route->getName()], $this->routes[$route->getIdentifier()]);
return $this;
}

Expand All @@ -181,11 +189,10 @@ public function removeNamedRoute(string $name): RouteCollectorInterface
*/
public function getNamedRoute(string $name): RouteInterface
{
foreach ($this->routes as $route) {
if ($name === $route->getName()) {
return $route;
}
if (isset($this->routesByName[$name])) {
return $this->routesByName[$name];
BusterNeece marked this conversation as resolved.
Show resolved Hide resolved
}

BusterNeece marked this conversation as resolved.
Show resolved Hide resolved
throw new RuntimeException('Named route does not exist for name: ' . $name);
}

Expand Down Expand Up @@ -229,6 +236,12 @@ public function map(array $methods, string $pattern, $handler): RouteInterface
{
$route = $this->createRoute($methods, $pattern, $handler);
$this->routes[$route->getIdentifier()] = $route;

$routeName = $route->getName();
if (null !== $routeName && !isset($this->routesByName[$routeName])) {
BusterNeece marked this conversation as resolved.
Show resolved Hide resolved
$this->routesByName[$routeName] = $route;
}

$this->routeCounter++;

return $route;
Expand Down