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';
55 * @param Application $application
56 * @param string|null $namespace
58 public function __construct(Application $application, $namespace = null)
60 $this->application = $application;
61 $this->namespace = $namespace;
67 public function getNamespaces()
69 if (null === $this->namespaces) {
70 $this->inspectApplication();
73 return $this->namespaces;
79 public function getCommands()
81 if (null === $this->commands) {
82 $this->inspectApplication();
85 return $this->commands;
93 * @throws CommandNotFoundException
95 public function getCommand($name)
97 if (!isset($this->commands[$name]) && !isset($this->aliases[$name])) {
98 throw new CommandNotFoundException(sprintf('Command %s does not exist.', $name));
101 return isset($this->commands[$name]) ? $this->commands[$name] : $this->aliases[$name];
104 private function inspectApplication()
106 $this->commands = array();
107 $this->namespaces = array();
109 $all = $this->application->all($this->namespace ? $this->application->findNamespace($this->namespace) : null);
110 foreach ($this->sortCommands($all) as $namespace => $commands) {
113 /** @var Command $command */
114 foreach ($commands as $name => $command) {
115 if (!$command->getName()) {
119 if ($command->getName() === $name) {
120 $this->commands[$name] = $command;
122 $this->aliases[$name] = $command;
128 $this->namespaces[$namespace] = array('id' => $namespace, 'commands' => $names);
133 * @param array $commands
137 private function sortCommands(array $commands)
139 $namespacedCommands = array();
140 $globalCommands = array();
141 foreach ($commands as $name => $command) {
142 $key = $this->application->extractNamespace($name, 1);
144 $globalCommands['_global'][$name] = $command;
146 $namespacedCommands[$key][$name] = $command;
149 ksort($namespacedCommands);
150 $namespacedCommands = array_merge($globalCommands, $namespacedCommands);
152 foreach ($namespacedCommands as &$commandsSet) {
155 // unset reference to keep scope clear
158 return $namespacedCommands;