From a1fcf67f2bd04094490277b6e4516b67e90c9b06 Mon Sep 17 00:00:00 2001 From: Eldad Fux Date: Sat, 4 Jul 2020 16:46:40 +0300 Subject: [PATCH] Route optimization --- src/App.php | 43 +++++++++++++++++++++++++++++-------------- 1 file changed, 29 insertions(+), 14 deletions(-) diff --git a/src/App.php b/src/App.php index 9332396a..21b54db1 100755 --- a/src/App.php +++ b/src/App.php @@ -107,6 +107,13 @@ class App '*' => [], ]; + /** + * Is Sorted? + * + * @var bool + */ + protected static $sorted = false; + /** * Route * @@ -422,6 +429,8 @@ protected static function addRoute($method, $url): Route self::$routes[$method][$url] = $route; + self::$sorted = false; + return $route; } @@ -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 */ @@ -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() : [];