4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Console\Descriptor;
14 use Symfony\Component\Console\Application;
15 use Symfony\Component\Console\Command\Command;
16 use Symfony\Component\Console\Exception\CommandNotFoundException;
19 * @author Jean-François Simon <jeanfrancois.simon@sensiolabs.com>
23 class ApplicationDescription
25 const GLOBAL_NAMESPACE = '_global';
47 * @param Application $application
48 * @param string|null $namespace
49 * @param bool $showHidden
51 public function __construct(Application $application, $namespace = null, $showHidden = false)
53 $this->application = $application;
54 $this->namespace = $namespace;
55 $this->showHidden = $showHidden;
61 public function getNamespaces()
63 if (null === $this->namespaces) {
64 $this->inspectApplication();
67 return $this->namespaces;
73 public function getCommands()
75 if (null === $this->commands) {
76 $this->inspectApplication();
79 return $this->commands;
87 * @throws CommandNotFoundException
89 public function getCommand($name)
91 if (!isset($this->commands[$name]) && !isset($this->aliases[$name])) {
92 throw new CommandNotFoundException(sprintf('Command %s does not exist.', $name));
95 return isset($this->commands[$name]) ? $this->commands[$name] : $this->aliases[$name];
98 private function inspectApplication()
100 $this->commands = array();
101 $this->namespaces = array();
103 $all = $this->application->all($this->namespace ? $this->application->findNamespace($this->namespace) : null);
104 foreach ($this->sortCommands($all) as $namespace => $commands) {
107 /** @var Command $command */
108 foreach ($commands as $name => $command) {
109 if (!$command->getName() || (!$this->showHidden && $command->isHidden())) {
113 if ($command->getName() === $name) {
114 $this->commands[$name] = $command;
116 $this->aliases[$name] = $command;
122 $this->namespaces[$namespace] = array('id' => $namespace, 'commands' => $names);
129 private function sortCommands(array $commands)
131 $namespacedCommands = array();
132 $globalCommands = array();
133 foreach ($commands as $name => $command) {
134 $key = $this->application->extractNamespace($name, 1);
136 $globalCommands['_global'][$name] = $command;
138 $namespacedCommands[$key][$name] = $command;
141 ksort($namespacedCommands);
142 $namespacedCommands = array_merge($globalCommands, $namespacedCommands);
144 foreach ($namespacedCommands as &$commandsSet) {
147 // unset reference to keep scope clear
150 return $namespacedCommands;