From 707c5bade0dd7220b6d7e03dd7e27d66840edeb0 Mon Sep 17 00:00:00 2001 From: Robin Chalas Date: Tue, 11 Feb 2020 11:52:39 +0100 Subject: [PATCH] [Console] Don't load same-namespace alternatives on exact match found --- src/Symfony/Component/Console/Application.php | 20 ++++++++++++--- .../Console/Tests/ApplicationTest.php | 25 +++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/src/Symfony/Component/Console/Application.php b/src/Symfony/Component/Console/Application.php index 1463967ffae0..280a34d5c5b1 100644 --- a/src/Symfony/Component/Console/Application.php +++ b/src/Symfony/Component/Console/Application.php @@ -645,7 +645,15 @@ public function find($name) // filter out aliases for commands which are already on the list if (\count($commands) > 1) { $commandList = $this->commandLoader ? array_merge(array_flip($this->commandLoader->getNames()), $this->commands) : $this->commands; - $commands = array_unique(array_filter($commands, function ($nameOrAlias) use (&$commandList, $commands, &$aliases) { + + if (isset($commandList[$name])) { + return $this->get($name); + } + + foreach ($commands as $k => $nameOrAlias) { + if ($nameOrAlias === $name) { + return $this->get($nameOrAlias); + } if (!$commandList[$nameOrAlias] instanceof Command) { $commandList[$nameOrAlias] = $this->commandLoader->get($nameOrAlias); } @@ -654,8 +662,14 @@ public function find($name) $aliases[$nameOrAlias] = $commandName; - return $commandName === $nameOrAlias || !\in_array($commandName, $commands); - })); + if ($commandName === $nameOrAlias || !\in_array($commandName, $commands)) { + continue; + } + + unset($commands[$k]); + } + + $commands = array_unique($commands); } $exact = \in_array($name, $commands, true) || isset($aliases[$name]); diff --git a/src/Symfony/Component/Console/Tests/ApplicationTest.php b/src/Symfony/Component/Console/Tests/ApplicationTest.php index 559c42599fbd..8288cfd3269f 100644 --- a/src/Symfony/Component/Console/Tests/ApplicationTest.php +++ b/src/Symfony/Component/Console/Tests/ApplicationTest.php @@ -1642,6 +1642,31 @@ public function testAllExcludesDisabledLazyCommand() $this->assertArrayNotHasKey('disabled', $application->all()); } + public function testFindAlternativesDoesNotLoadSameNamespaceCommandsOnExactMatch() + { + $application = new Application(); + $application->setAutoExit(false); + + $loaded = []; + + $application->setCommandLoader(new FactoryCommandLoader([ + 'foo:bar' => function () use (&$loaded) { + $loaded['foo:bar'] = true; + + return (new Command('foo:bar'))->setCode(function () {}); + }, + 'foo' => function () use (&$loaded) { + $loaded['foo'] = true; + + return (new Command('foo'))->setCode(function () {}); + }, + ])); + + $application->run(new ArrayInput(['command' => 'foo']), new NullOutput()); + + $this->assertSame(['foo' => true], $loaded); + } + protected function getDispatcher($skipCommand = false) { $dispatcher = new EventDispatcher();