From 5727c4edf82c38e72a4891024c51070c5db3238a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mr=C2=B7x?= Date: Mon, 30 Aug 2021 17:20:22 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=B9=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- http-helper/Route/Router.php | 28 +++++++++++++++------------- http-server/Message/Uri.php | 2 +- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/http-helper/Route/Router.php b/http-helper/Route/Router.php index b0983e32..2a129c39 100644 --- a/http-helper/Route/Router.php +++ b/http-helper/Route/Router.php @@ -93,9 +93,6 @@ class Router extends HttpService implements RouterInterface */ public function addRoute($path, $handler, string $method = 'any'): ?Node { - if (!isset($this->nodes[$method])) { - $this->nodes[$method] = []; - } if ($handler instanceof Closure) { $handler = Closure::bind($handler, di(Controller::class)); } @@ -130,14 +127,16 @@ class Router extends HttpService implements RouterInterface private function tree($path, $handler, string $method = 'any'): Node { $explode = $this->split($path); - if (!isset($this->nodes['/'])) { - $this->nodes['/'] = $this->NodeInstance('/', 0, $method); + $start = array_shift($explode); + $parent = $this->nodes[$start] ?? null; + if (is_null($parent)) { + $parent = $this->nodes[$start] = $this->NodeInstance($start, 0, $method); } - $parent = $this->nodes['/']; - if (!empty($explode)) { - $parent = $this->bindNode($parent, $explode, $method); + if (empty($explode)) { + return $parent->setHandler($handler, $method, $path); } - return $parent->setHandler($handler, $method, $path); + return $this->bindNode($parent, $explode, $method) + ->setHandler($handler, $method, $path); } @@ -396,10 +395,13 @@ class Router extends HttpService implements RouterInterface */ public function tree_search(?array $explode): ?Node { - if (!isset($this->nodes['/'])) { + if (empty($this->nodes)) { + return null; + } + $parent = $this->nodes[array_shift($explode)]; + if (!($parent instanceof Node)) { return null; } - $parent = $this->nodes['/']; while ($value = array_shift($explode)) { $node = $parent->findNode($value); if (!$node) { @@ -418,13 +420,13 @@ class Router extends HttpService implements RouterInterface { $path = $this->addPrefix() . '/' . ltrim($path, '/'); if ($path === '/') { - return []; + return ['/']; } $filter = array_filter(explode('/', $path)); if (!empty($filter)) { return $filter; } - return []; + return ['/']; } /** diff --git a/http-server/Message/Uri.php b/http-server/Message/Uri.php index 8e473d67..9fd2f4a7 100644 --- a/http-server/Message/Uri.php +++ b/http-server/Message/Uri.php @@ -41,7 +41,7 @@ class Uri implements UriInterface public function getExplode(): array { if ($this->path == '/' || $this->path == '') { - return ['']; + return ['/']; } if (empty($this->_explode)) { $this->_explode = array_filter(explode('/', $this->path));