diff --git a/system/Router/RouteCollection.php b/system/Router/RouteCollection.php index 7dd87701a432..c688ed88a04f 100644 --- a/system/Router/RouteCollection.php +++ b/system/Router/RouteCollection.php @@ -1577,41 +1577,52 @@ public function setPrioritize(bool $enabled = true) * Get all controllers in Route Handlers * * @param string|null $verb HTTP verb. `'*'` returns all controllers in any verb. + * + * @return array controller name list + * @phpstan-return list */ public function getRegisteredControllers(?string $verb = '*'): array { - $routes = []; + $controllers = []; if ($verb === '*') { - $rawRoutes = []; - foreach ($this->defaultHTTPMethods as $tmpVerb) { - $rawRoutes = array_merge($rawRoutes, $this->routes[$tmpVerb]); - } - - foreach ($rawRoutes as $route) { - $key = key($route['route']); - $handler = $route['route'][$key]; - - $routes[$key] = $handler; + foreach ($this->routes[$tmpVerb] as $route) { + $routeKey = key($route['route']); + $controller = $this->getControllerName($route['route'][$routeKey]); + if ($controller !== null) { + $controllers[] = $controller; + } + } } } else { $routes = $this->getRoutes($verb); - } - - $controllers = []; - foreach ($routes as $handler) { - if (! is_string($handler)) { - continue; + foreach ($routes as $handler) { + $controller = $this->getControllerName($handler); + if ($controller !== null) { + $controllers[] = $controller; + } } + } - [$controller] = explode('::', $handler, 2); + return array_unique($controllers); + } - $controllers[] = $controller; + /** + * @param Closure|string $handler Handler + * + * @return string|null Controller classname + */ + private function getControllerName($handler) + { + if (! is_string($handler)) { + return null; } - return array_unique($controllers); + [$controller] = explode('::', $handler, 2); + + return $controller; } /** diff --git a/tests/system/Router/RouteCollectionTest.php b/tests/system/Router/RouteCollectionTest.php index 70d378467414..6458449a02c9 100644 --- a/tests/system/Router/RouteCollectionTest.php +++ b/tests/system/Router/RouteCollectionTest.php @@ -1782,15 +1782,16 @@ public function testGetRegisteredControllersReturnsOneControllerWhenTwoRoutsWith public function testGetRegisteredControllersReturnsAllControllers() { $collection = $this->getCollector(); - $collection->get('test', '\App\Controllers\Hello::get'); - $collection->post('test', '\App\Controllers\Hello::post'); - $collection->post('hello', '\App\Controllers\Test::hello'); + $collection->get('test', '\App\Controllers\HelloGet::get'); + $collection->post('test', '\App\Controllers\HelloPost::post'); + $collection->post('hello', '\App\Controllers\TestPost::hello'); $routes = $collection->getRegisteredControllers('*'); $expects = [ - '\App\Controllers\Hello', - '\App\Controllers\Test', + '\App\Controllers\HelloGet', + '\App\Controllers\HelloPost', + '\App\Controllers\TestPost', ]; $this->assertSame($expects, $routes); }