Skip to content

Commit

Permalink
Route optimization
Browse files Browse the repository at this point in the history
  • Loading branch information
eldadfux committed Jul 4, 2020
1 parent f9fe309 commit a1fcf67
Showing 1 changed file with 29 additions and 14 deletions.
43 changes: 29 additions & 14 deletions src/App.php
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,13 @@ class App
'*' => [],
];

/**
* Is Sorted?
*
* @var bool
*/
protected static $sorted = false;

/**
* Route
*
Expand Down Expand Up @@ -422,6 +429,8 @@ protected static function addRoute($method, $url): Route

self::$routes[$method][$url] = $route;

self::$sorted = false;

return $route;
}

Expand All @@ -447,20 +456,6 @@ public function match(Request $request)
self::$routes[$method] = [];
}

/*
* Re-order array
*
* For route to work with similar links where one is shorter than other
* but both might match given pattern
*/
\uksort(self::$routes[$method], function ($a, $b) {
return \strlen($b) - \strlen($a);
});

\uksort(self::$routes[$method], function ($a, $b) {
return \count(\explode('/', $b)) - \count(\explode('/', $a));
});

foreach (self::$routes[$method] as $route) {
/* @var $route Route */

Expand Down Expand Up @@ -578,6 +573,26 @@ public function run(Request $request, Response $response): self
$this->resources['request'] = $request;
$this->resources['response'] = $response;

/*
* Re-order array
*
* For route to work with similar links where one is shorter than other
* but both might match given pattern
*/
if(!self::$sorted) {
foreach (self::$routes as $method => $list) {
\uksort(self::$routes[$method], function ($a, $b) {
return \strlen($b) - \strlen($a);
});

\uksort(self::$routes[$method], function ($a, $b) {
return \count(\explode('/', $b)) - \count(\explode('/', $a));
});
}

self::$sorted = true;
}

$method = $request->getServer('REQUEST_METHOD', '');
$route = $this->match($request);
$groups = ($route instanceof Route) ? $route->getGroups() : [];
Expand Down

0 comments on commit a1fcf67

Please sign in to comment.