Rajout de doctrine/orm
[zf2.biz/galerie.git] / vendor / symfony / console / Symfony / Component / Console / Application.php
1 <?php
2
3 /*
4  * This file is part of the Symfony package.
5  *
6  * (c) Fabien Potencier <fabien@symfony.com>
7  *
8  * For the full copyright and license information, please view the LICENSE
9  * file that was distributed with this source code.
10  */
11
12 namespace Symfony\Component\Console;
13
14 use Symfony\Component\Console\Input\InputInterface;
15 use Symfony\Component\Console\Input\ArgvInput;
16 use Symfony\Component\Console\Input\ArrayInput;
17 use Symfony\Component\Console\Input\InputDefinition;
18 use Symfony\Component\Console\Input\InputOption;
19 use Symfony\Component\Console\Input\InputArgument;
20 use Symfony\Component\Console\Output\OutputInterface;
21 use Symfony\Component\Console\Output\Output;
22 use Symfony\Component\Console\Output\ConsoleOutput;
23 use Symfony\Component\Console\Output\ConsoleOutputInterface;
24 use Symfony\Component\Console\Command\Command;
25 use Symfony\Component\Console\Command\HelpCommand;
26 use Symfony\Component\Console\Command\ListCommand;
27 use Symfony\Component\Console\Helper\HelperSet;
28 use Symfony\Component\Console\Helper\FormatterHelper;
29 use Symfony\Component\Console\Helper\DialogHelper;
30
31 /**
32  * An Application is the container for a collection of commands.
33  *
34  * It is the main entry point of a Console application.
35  *
36  * This class is optimized for a standard CLI environment.
37  *
38  * Usage:
39  *
40  *     $app = new Application('myapp', '1.0 (stable)');
41  *     $app->add(new SimpleCommand());
42  *     $app->run();
43  *
44  * @author Fabien Potencier <fabien@symfony.com>
45  *
46  * @api
47  */
48 class Application
49 {
50     private $commands;
51     private $wantHelps = false;
52     private $runningCommand;
53     private $name;
54     private $version;
55     private $catchExceptions;
56     private $autoExit;
57     private $definition;
58     private $helperSet;
59
60     /**
61      * Constructor.
62      *
63      * @param string $name    The name of the application
64      * @param string $version The version of the application
65      *
66      * @api
67      */
68     public function __construct($name = 'UNKNOWN', $version = 'UNKNOWN')
69     {
70         $this->name = $name;
71         $this->version = $version;
72         $this->catchExceptions = true;
73         $this->autoExit = true;
74         $this->commands = array();
75         $this->helperSet = $this->getDefaultHelperSet();
76         $this->definition = $this->getDefaultInputDefinition();
77
78         foreach ($this->getDefaultCommands() as $command) {
79             $this->add($command);
80         }
81     }
82
83     /**
84      * Runs the current application.
85      *
86      * @param InputInterface  $input  An Input instance
87      * @param OutputInterface $output An Output instance
88      *
89      * @return integer 0 if everything went fine, or an error code
90      *
91      * @throws \Exception When doRun returns Exception
92      *
93      * @api
94      */
95     public function run(InputInterface $input = null, OutputInterface $output = null)
96     {
97         if (null === $input) {
98             $input = new ArgvInput();
99         }
100
101         if (null === $output) {
102             $output = new ConsoleOutput();
103         }
104
105         try {
106             $statusCode = $this->doRun($input, $output);
107         } catch (\Exception $e) {
108             if (!$this->catchExceptions) {
109                 throw $e;
110             }
111
112             if ($output instanceof ConsoleOutputInterface) {
113                 $this->renderException($e, $output->getErrorOutput());
114             } else {
115                 $this->renderException($e, $output);
116             }
117             $statusCode = $e->getCode();
118
119             $statusCode = is_numeric($statusCode) && $statusCode ? $statusCode : 1;
120         }
121
122         if ($this->autoExit) {
123             if ($statusCode > 255) {
124                 $statusCode = 255;
125             }
126             // @codeCoverageIgnoreStart
127             exit($statusCode);
128             // @codeCoverageIgnoreEnd
129         }
130
131         return $statusCode;
132     }
133
134     /**
135      * Runs the current application.
136      *
137      * @param InputInterface  $input  An Input instance
138      * @param OutputInterface $output An Output instance
139      *
140      * @return integer 0 if everything went fine, or an error code
141      */
142     public function doRun(InputInterface $input, OutputInterface $output)
143     {
144         $name = $this->getCommandName($input);
145
146         if (true === $input->hasParameterOption(array('--ansi'))) {
147             $output->setDecorated(true);
148         } elseif (true === $input->hasParameterOption(array('--no-ansi'))) {
149             $output->setDecorated(false);
150         }
151
152         if (true === $input->hasParameterOption(array('--help', '-h'))) {
153             if (!$name) {
154                 $name = 'help';
155                 $input = new ArrayInput(array('command' => 'help'));
156             } else {
157                 $this->wantHelps = true;
158             }
159         }
160
161         if (true === $input->hasParameterOption(array('--no-interaction', '-n'))) {
162             $input->setInteractive(false);
163         }
164
165         if (function_exists('posix_isatty') && $this->getHelperSet()->has('dialog')) {
166             $inputStream = $this->getHelperSet()->get('dialog')->getInputStream();
167             if (!posix_isatty($inputStream)) {
168                 $input->setInteractive(false);
169             }
170         }
171
172         if (true === $input->hasParameterOption(array('--quiet', '-q'))) {
173             $output->setVerbosity(OutputInterface::VERBOSITY_QUIET);
174         } elseif (true === $input->hasParameterOption(array('--verbose', '-v'))) {
175             $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
176         }
177
178         if (true === $input->hasParameterOption(array('--version', '-V'))) {
179             $output->writeln($this->getLongVersion());
180
181             return 0;
182         }
183
184         if (!$name) {
185             $name = 'list';
186             $input = new ArrayInput(array('command' => 'list'));
187         }
188
189         // the command name MUST be the first element of the input
190         $command = $this->find($name);
191
192         $this->runningCommand = $command;
193         $statusCode = $command->run($input, $output);
194         $this->runningCommand = null;
195
196         return is_numeric($statusCode) ? $statusCode : 0;
197     }
198
199     /**
200      * Set a helper set to be used with the command.
201      *
202      * @param HelperSet $helperSet The helper set
203      *
204      * @api
205      */
206     public function setHelperSet(HelperSet $helperSet)
207     {
208         $this->helperSet = $helperSet;
209     }
210
211     /**
212      * Get the helper set associated with the command.
213      *
214      * @return HelperSet The HelperSet instance associated with this command
215      *
216      * @api
217      */
218     public function getHelperSet()
219     {
220         return $this->helperSet;
221     }
222
223     /**
224      * Gets the InputDefinition related to this Application.
225      *
226      * @return InputDefinition The InputDefinition instance
227      */
228     public function getDefinition()
229     {
230         return $this->definition;
231     }
232
233     /**
234      * Gets the help message.
235      *
236      * @return string A help message.
237      */
238     public function getHelp()
239     {
240         $messages = array(
241             $this->getLongVersion(),
242             '',
243             '<comment>Usage:</comment>',
244             sprintf("  [options] command [arguments]\n"),
245             '<comment>Options:</comment>',
246         );
247
248         foreach ($this->getDefinition()->getOptions() as $option) {
249             $messages[] = sprintf('  %-29s %s %s',
250                 '<info>--'.$option->getName().'</info>',
251                 $option->getShortcut() ? '<info>-'.$option->getShortcut().'</info>' : '  ',
252                 $option->getDescription()
253             );
254         }
255
256         return implode(PHP_EOL, $messages);
257     }
258
259     /**
260      * Sets whether to catch exceptions or not during commands execution.
261      *
262      * @param Boolean $boolean Whether to catch exceptions or not during commands execution
263      *
264      * @api
265      */
266     public function setCatchExceptions($boolean)
267     {
268         $this->catchExceptions = (Boolean) $boolean;
269     }
270
271     /**
272      * Sets whether to automatically exit after a command execution or not.
273      *
274      * @param Boolean $boolean Whether to automatically exit after a command execution or not
275      *
276      * @api
277      */
278     public function setAutoExit($boolean)
279     {
280         $this->autoExit = (Boolean) $boolean;
281     }
282
283     /**
284      * Gets the name of the application.
285      *
286      * @return string The application name
287      *
288      * @api
289      */
290     public function getName()
291     {
292         return $this->name;
293     }
294
295     /**
296      * Sets the application name.
297      *
298      * @param string $name The application name
299      *
300      * @api
301      */
302     public function setName($name)
303     {
304         $this->name = $name;
305     }
306
307     /**
308      * Gets the application version.
309      *
310      * @return string The application version
311      *
312      * @api
313      */
314     public function getVersion()
315     {
316         return $this->version;
317     }
318
319     /**
320      * Sets the application version.
321      *
322      * @param string $version The application version
323      *
324      * @api
325      */
326     public function setVersion($version)
327     {
328         $this->version = $version;
329     }
330
331     /**
332      * Returns the long version of the application.
333      *
334      * @return string The long application version
335      *
336      * @api
337      */
338     public function getLongVersion()
339     {
340         if ('UNKNOWN' !== $this->getName() && 'UNKNOWN' !== $this->getVersion()) {
341             return sprintf('<info>%s</info> version <comment>%s</comment>', $this->getName(), $this->getVersion());
342         }
343
344         return '<info>Console Tool</info>';
345     }
346
347     /**
348      * Registers a new command.
349      *
350      * @param string $name The command name
351      *
352      * @return Command The newly created command
353      *
354      * @api
355      */
356     public function register($name)
357     {
358         return $this->add(new Command($name));
359     }
360
361     /**
362      * Adds an array of command objects.
363      *
364      * @param Command[] $commands An array of commands
365      *
366      * @api
367      */
368     public function addCommands(array $commands)
369     {
370         foreach ($commands as $command) {
371             $this->add($command);
372         }
373     }
374
375     /**
376      * Adds a command object.
377      *
378      * If a command with the same name already exists, it will be overridden.
379      *
380      * @param Command $command A Command object
381      *
382      * @return Command The registered command
383      *
384      * @api
385      */
386     public function add(Command $command)
387     {
388         $command->setApplication($this);
389
390         if (!$command->isEnabled()) {
391             $command->setApplication(null);
392
393             return;
394         }
395
396         $this->commands[$command->getName()] = $command;
397
398         foreach ($command->getAliases() as $alias) {
399             $this->commands[$alias] = $command;
400         }
401
402         return $command;
403     }
404
405     /**
406      * Returns a registered command by name or alias.
407      *
408      * @param string $name The command name or alias
409      *
410      * @return Command A Command object
411      *
412      * @throws \InvalidArgumentException When command name given does not exist
413      *
414      * @api
415      */
416     public function get($name)
417     {
418         if (!isset($this->commands[$name])) {
419             throw new \InvalidArgumentException(sprintf('The command "%s" does not exist.', $name));
420         }
421
422         $command = $this->commands[$name];
423
424         if ($this->wantHelps) {
425             $this->wantHelps = false;
426
427             $helpCommand = $this->get('help');
428             $helpCommand->setCommand($command);
429
430             return $helpCommand;
431         }
432
433         return $command;
434     }
435
436     /**
437      * Returns true if the command exists, false otherwise.
438      *
439      * @param string $name The command name or alias
440      *
441      * @return Boolean true if the command exists, false otherwise
442      *
443      * @api
444      */
445     public function has($name)
446     {
447         return isset($this->commands[$name]);
448     }
449
450     /**
451      * Returns an array of all unique namespaces used by currently registered commands.
452      *
453      * It does not returns the global namespace which always exists.
454      *
455      * @return array An array of namespaces
456      */
457     public function getNamespaces()
458     {
459         $namespaces = array();
460         foreach ($this->commands as $command) {
461             $namespaces[] = $this->extractNamespace($command->getName());
462
463             foreach ($command->getAliases() as $alias) {
464                 $namespaces[] = $this->extractNamespace($alias);
465             }
466         }
467
468         return array_values(array_unique(array_filter($namespaces)));
469     }
470
471     /**
472      * Finds a registered namespace by a name or an abbreviation.
473      *
474      * @param string $namespace A namespace or abbreviation to search for
475      *
476      * @return string A registered namespace
477      *
478      * @throws \InvalidArgumentException When namespace is incorrect or ambiguous
479      */
480     public function findNamespace($namespace)
481     {
482         $allNamespaces = array();
483         foreach ($this->getNamespaces() as $n) {
484             $allNamespaces[$n] = explode(':', $n);
485         }
486
487         $found = array();
488         foreach (explode(':', $namespace) as $i => $part) {
489             $abbrevs = static::getAbbreviations(array_unique(array_values(array_filter(array_map(function ($p) use ($i) { return isset($p[$i]) ? $p[$i] : ''; }, $allNamespaces)))));
490
491             if (!isset($abbrevs[$part])) {
492                 $message = sprintf('There are no commands defined in the "%s" namespace.', $namespace);
493
494                 if (1 <= $i) {
495                     $part = implode(':', $found).':'.$part;
496                 }
497
498                 if ($alternatives = $this->findAlternativeNamespace($part, $abbrevs)) {
499                     if (1 == count($alternatives)) {
500                         $message .= "\n\nDid you mean this?\n    ";
501                     } else {
502                         $message .= "\n\nDid you mean one of these?\n    ";
503                     }
504
505                     $message .= implode("\n    ", $alternatives);
506                 }
507
508                 throw new \InvalidArgumentException($message);
509             }
510
511             if (count($abbrevs[$part]) > 1) {
512                 throw new \InvalidArgumentException(sprintf('The namespace "%s" is ambiguous (%s).', $namespace, $this->getAbbreviationSuggestions($abbrevs[$part])));
513             }
514
515             $found[] = $abbrevs[$part][0];
516         }
517
518         return implode(':', $found);
519     }
520
521     /**
522      * Finds a command by name or alias.
523      *
524      * Contrary to get, this command tries to find the best
525      * match if you give it an abbreviation of a name or alias.
526      *
527      * @param string $name A command name or a command alias
528      *
529      * @return Command A Command instance
530      *
531      * @throws \InvalidArgumentException When command name is incorrect or ambiguous
532      *
533      * @api
534      */
535     public function find($name)
536     {
537         // namespace
538         $namespace = '';
539         $searchName = $name;
540         if (false !== $pos = strrpos($name, ':')) {
541             $namespace = $this->findNamespace(substr($name, 0, $pos));
542             $searchName = $namespace.substr($name, $pos);
543         }
544
545         // name
546         $commands = array();
547         foreach ($this->commands as $command) {
548             if ($this->extractNamespace($command->getName()) == $namespace) {
549                 $commands[] = $command->getName();
550             }
551         }
552
553         $abbrevs = static::getAbbreviations(array_unique($commands));
554         if (isset($abbrevs[$searchName]) && 1 == count($abbrevs[$searchName])) {
555             return $this->get($abbrevs[$searchName][0]);
556         }
557
558         if (isset($abbrevs[$searchName]) && count($abbrevs[$searchName]) > 1) {
559             $suggestions = $this->getAbbreviationSuggestions($abbrevs[$searchName]);
560
561             throw new \InvalidArgumentException(sprintf('Command "%s" is ambiguous (%s).', $name, $suggestions));
562         }
563
564         // aliases
565         $aliases = array();
566         foreach ($this->commands as $command) {
567             foreach ($command->getAliases() as $alias) {
568                 if ($this->extractNamespace($alias) == $namespace) {
569                     $aliases[] = $alias;
570                 }
571             }
572         }
573
574         $aliases = static::getAbbreviations(array_unique($aliases));
575         if (!isset($aliases[$searchName])) {
576             $message = sprintf('Command "%s" is not defined.', $name);
577
578             if ($alternatives = $this->findAlternativeCommands($searchName, $abbrevs)) {
579                 if (1 == count($alternatives)) {
580                     $message .= "\n\nDid you mean this?\n    ";
581                 } else {
582                     $message .= "\n\nDid you mean one of these?\n    ";
583                 }
584                 $message .= implode("\n    ", $alternatives);
585             }
586
587             throw new \InvalidArgumentException($message);
588         }
589
590         if (count($aliases[$searchName]) > 1) {
591             throw new \InvalidArgumentException(sprintf('Command "%s" is ambiguous (%s).', $name, $this->getAbbreviationSuggestions($aliases[$searchName])));
592         }
593
594         return $this->get($aliases[$searchName][0]);
595     }
596
597     /**
598      * Gets the commands (registered in the given namespace if provided).
599      *
600      * The array keys are the full names and the values the command instances.
601      *
602      * @param string $namespace A namespace name
603      *
604      * @return array An array of Command instances
605      *
606      * @api
607      */
608     public function all($namespace = null)
609     {
610         if (null === $namespace) {
611             return $this->commands;
612         }
613
614         $commands = array();
615         foreach ($this->commands as $name => $command) {
616             if ($namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1)) {
617                 $commands[$name] = $command;
618             }
619         }
620
621         return $commands;
622     }
623
624     /**
625      * Returns an array of possible abbreviations given a set of names.
626      *
627      * @param array $names An array of names
628      *
629      * @return array An array of abbreviations
630      */
631     public static function getAbbreviations($names)
632     {
633         $abbrevs = array();
634         foreach ($names as $name) {
635             for ($len = strlen($name) - 1; $len > 0; --$len) {
636                 $abbrev = substr($name, 0, $len);
637                 if (!isset($abbrevs[$abbrev])) {
638                     $abbrevs[$abbrev] = array($name);
639                 } else {
640                     $abbrevs[$abbrev][] = $name;
641                 }
642             }
643         }
644
645         // Non-abbreviations always get entered, even if they aren't unique
646         foreach ($names as $name) {
647             $abbrevs[$name] = array($name);
648         }
649
650         return $abbrevs;
651     }
652
653     /**
654      * Returns a text representation of the Application.
655      *
656      * @param string  $namespace An optional namespace name
657      * @param boolean $raw       Whether to return raw command list
658      *
659      * @return string A string representing the Application
660      */
661     public function asText($namespace = null, $raw = false)
662     {
663         $commands = $namespace ? $this->all($this->findNamespace($namespace)) : $this->commands;
664
665         $width = 0;
666         foreach ($commands as $command) {
667             $width = strlen($command->getName()) > $width ? strlen($command->getName()) : $width;
668         }
669         $width += 2;
670
671         if ($raw) {
672             $messages = array();
673             foreach ($this->sortCommands($commands) as $space => $commands) {
674                 foreach ($commands as $name => $command) {
675                     $messages[] = sprintf("%-${width}s %s", $name, $command->getDescription());
676                 }
677             }
678
679             return implode(PHP_EOL, $messages);
680         }
681
682         $messages = array($this->getHelp(), '');
683         if ($namespace) {
684             $messages[] = sprintf("<comment>Available commands for the \"%s\" namespace:</comment>", $namespace);
685         } else {
686             $messages[] = '<comment>Available commands:</comment>';
687         }
688
689         // add commands by namespace
690         foreach ($this->sortCommands($commands) as $space => $commands) {
691             if (!$namespace && '_global' !== $space) {
692                 $messages[] = '<comment>'.$space.'</comment>';
693             }
694
695             foreach ($commands as $name => $command) {
696                 $messages[] = sprintf("  <info>%-${width}s</info> %s", $name, $command->getDescription());
697             }
698         }
699
700         return implode(PHP_EOL, $messages);
701     }
702
703     /**
704      * Returns an XML representation of the Application.
705      *
706      * @param string  $namespace An optional namespace name
707      * @param Boolean $asDom     Whether to return a DOM or an XML string
708      *
709      * @return string|DOMDocument An XML string representing the Application
710      */
711     public function asXml($namespace = null, $asDom = false)
712     {
713         $commands = $namespace ? $this->all($this->findNamespace($namespace)) : $this->commands;
714
715         $dom = new \DOMDocument('1.0', 'UTF-8');
716         $dom->formatOutput = true;
717         $dom->appendChild($xml = $dom->createElement('symfony'));
718
719         $xml->appendChild($commandsXML = $dom->createElement('commands'));
720
721         if ($namespace) {
722             $commandsXML->setAttribute('namespace', $namespace);
723         } else {
724             $namespacesXML = $dom->createElement('namespaces');
725             $xml->appendChild($namespacesXML);
726         }
727
728         // add commands by namespace
729         foreach ($this->sortCommands($commands) as $space => $commands) {
730             if (!$namespace) {
731                 $namespaceArrayXML = $dom->createElement('namespace');
732                 $namespacesXML->appendChild($namespaceArrayXML);
733                 $namespaceArrayXML->setAttribute('id', $space);
734             }
735
736             foreach ($commands as $name => $command) {
737                 if ($name !== $command->getName()) {
738                     continue;
739                 }
740
741                 if (!$namespace) {
742                     $commandXML = $dom->createElement('command');
743                     $namespaceArrayXML->appendChild($commandXML);
744                     $commandXML->appendChild($dom->createTextNode($name));
745                 }
746
747                 $node = $command->asXml(true)->getElementsByTagName('command')->item(0);
748                 $node = $dom->importNode($node, true);
749
750                 $commandsXML->appendChild($node);
751             }
752         }
753
754         return $asDom ? $dom : $dom->saveXml();
755     }
756
757     /**
758      * Renders a caught exception.
759      *
760      * @param Exception       $e      An exception instance
761      * @param OutputInterface $output An OutputInterface instance
762      */
763     public function renderException($e, $output)
764     {
765         $strlen = function ($string) {
766             if (!function_exists('mb_strlen')) {
767                 return strlen($string);
768             }
769
770             if (false === $encoding = mb_detect_encoding($string)) {
771                 return strlen($string);
772             }
773
774             return mb_strlen($string, $encoding);
775         };
776
777         do {
778             $title = sprintf('  [%s]  ', get_class($e));
779             $len = $strlen($title);
780             $width = $this->getTerminalWidth() ? $this->getTerminalWidth() - 1 : PHP_INT_MAX;
781             $lines = array();
782             foreach (preg_split("{\r?\n}", $e->getMessage()) as $line) {
783                 foreach (str_split($line, $width - 4) as $line) {
784                     $lines[] = sprintf('  %s  ', $line);
785                     $len = max($strlen($line) + 4, $len);
786                 }
787             }
788
789             $messages = array(str_repeat(' ', $len), $title.str_repeat(' ', max(0, $len - $strlen($title))));
790
791             foreach ($lines as $line) {
792                 $messages[] = $line.str_repeat(' ', $len - $strlen($line));
793             }
794
795             $messages[] = str_repeat(' ', $len);
796
797             $output->writeln("");
798             $output->writeln("");
799             foreach ($messages as $message) {
800                 $output->writeln('<error>'.$message.'</error>');
801             }
802             $output->writeln("");
803             $output->writeln("");
804
805             if (OutputInterface::VERBOSITY_VERBOSE === $output->getVerbosity()) {
806                 $output->writeln('<comment>Exception trace:</comment>');
807
808                 // exception related properties
809                 $trace = $e->getTrace();
810                 array_unshift($trace, array(
811                     'function' => '',
812                     'file'     => $e->getFile() != null ? $e->getFile() : 'n/a',
813                     'line'     => $e->getLine() != null ? $e->getLine() : 'n/a',
814                     'args'     => array(),
815                 ));
816
817                 for ($i = 0, $count = count($trace); $i < $count; $i++) {
818                     $class = isset($trace[$i]['class']) ? $trace[$i]['class'] : '';
819                     $type = isset($trace[$i]['type']) ? $trace[$i]['type'] : '';
820                     $function = $trace[$i]['function'];
821                     $file = isset($trace[$i]['file']) ? $trace[$i]['file'] : 'n/a';
822                     $line = isset($trace[$i]['line']) ? $trace[$i]['line'] : 'n/a';
823
824                     $output->writeln(sprintf(' %s%s%s() at <info>%s:%s</info>', $class, $type, $function, $file, $line));
825                 }
826
827                 $output->writeln("");
828                 $output->writeln("");
829             }
830         } while ($e = $e->getPrevious());
831
832         if (null !== $this->runningCommand) {
833             $output->writeln(sprintf('<info>%s</info>', sprintf($this->runningCommand->getSynopsis(), $this->getName())));
834             $output->writeln("");
835             $output->writeln("");
836         }
837     }
838
839     /**
840      * Tries to figure out the terminal width in which this application runs
841      *
842      * @return int|null
843      */
844     protected function getTerminalWidth()
845     {
846         if (defined('PHP_WINDOWS_VERSION_BUILD')) {
847             if ($ansicon = getenv('ANSICON')) {
848                 return preg_replace('{^(\d+)x.*$}', '$1', $ansicon);
849             }
850
851             exec('mode CON', $execData);
852             if (preg_match('{columns:\s*(\d+)}i', $execData[4], $matches)) {
853                 return $matches[1];
854             }
855         }
856
857         if (preg_match("{rows.(\d+);.columns.(\d+);}i", $this->getSttyColumns(), $match)) {
858             return $match[2];
859         }
860     }
861
862     /**
863      * Tries to figure out the terminal height in which this application runs
864      *
865      * @return int|null
866      */
867     protected function getTerminalHeight()
868     {
869         if (defined('PHP_WINDOWS_VERSION_BUILD')) {
870             if ($ansicon = getenv('ANSICON')) {
871                 return preg_replace('{^\d+x\d+ \(\d+x(\d+)\)$}', '$1', trim($ansicon));
872             }
873
874             exec('mode CON', $execData);
875             if (preg_match('{lines:\s*(\d+)}i', $execData[3], $matches)) {
876                 return $matches[1];
877             }
878         }
879
880         if (preg_match("{rows.(\d+);.columns.(\d+);}i", $this->getSttyColumns(), $match)) {
881             return $match[1];
882         }
883     }
884
885     /**
886      * Gets the name of the command based on input.
887      *
888      * @param InputInterface $input The input interface
889      *
890      * @return string The command name
891      */
892     protected function getCommandName(InputInterface $input)
893     {
894         return $input->getFirstArgument();
895     }
896
897     /**
898      * Gets the default input definition.
899      *
900      * @return InputDefinition An InputDefinition instance
901      */
902     protected function getDefaultInputDefinition()
903     {
904         return new InputDefinition(array(
905             new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'),
906
907             new InputOption('--help',           '-h', InputOption::VALUE_NONE, 'Display this help message.'),
908             new InputOption('--quiet',          '-q', InputOption::VALUE_NONE, 'Do not output any message.'),
909             new InputOption('--verbose',        '-v', InputOption::VALUE_NONE, 'Increase verbosity of messages.'),
910             new InputOption('--version',        '-V', InputOption::VALUE_NONE, 'Display this application version.'),
911             new InputOption('--ansi',           '',   InputOption::VALUE_NONE, 'Force ANSI output.'),
912             new InputOption('--no-ansi',        '',   InputOption::VALUE_NONE, 'Disable ANSI output.'),
913             new InputOption('--no-interaction', '-n', InputOption::VALUE_NONE, 'Do not ask any interactive question.'),
914         ));
915     }
916
917     /**
918      * Gets the default commands that should always be available.
919      *
920      * @return array An array of default Command instances
921      */
922     protected function getDefaultCommands()
923     {
924         return array(new HelpCommand(), new ListCommand());
925     }
926
927     /**
928      * Gets the default helper set with the helpers that should always be available.
929      *
930      * @return HelperSet A HelperSet instance
931      */
932     protected function getDefaultHelperSet()
933     {
934         return new HelperSet(array(
935             new FormatterHelper(),
936             new DialogHelper(),
937         ));
938     }
939
940     /**
941      * Runs and parses stty -a if it's available, suppressing any error output
942      *
943      * @return string
944      */
945     private function getSttyColumns()
946     {
947         if (!function_exists('proc_open')) {
948             return;
949         }
950
951         $descriptorspec = array(1 => array('pipe', 'w'), 2 => array('pipe', 'w'));
952         $process = proc_open('stty -a | grep columns', $descriptorspec, $pipes, null, null, array('suppress_errors' => true));
953         if (is_resource($process)) {
954             $info = stream_get_contents($pipes[1]);
955             fclose($pipes[1]);
956             fclose($pipes[2]);
957             proc_close($process);
958
959             return $info;
960         }
961     }
962
963     /**
964      * Sorts commands in alphabetical order.
965      *
966      * @param array $commands An associative array of commands to sort
967      *
968      * @return array A sorted array of commands
969      */
970     private function sortCommands($commands)
971     {
972         $namespacedCommands = array();
973         foreach ($commands as $name => $command) {
974             $key = $this->extractNamespace($name, 1);
975             if (!$key) {
976                 $key = '_global';
977             }
978
979             $namespacedCommands[$key][$name] = $command;
980         }
981         ksort($namespacedCommands);
982
983         foreach ($namespacedCommands as &$commands) {
984             ksort($commands);
985         }
986
987         return $namespacedCommands;
988     }
989
990     /**
991      * Returns abbreviated suggestions in string format.
992      *
993      * @param array $abbrevs Abbreviated suggestions to convert
994      *
995      * @return string A formatted string of abbreviated suggestions
996      */
997     private function getAbbreviationSuggestions($abbrevs)
998     {
999         return sprintf('%s, %s%s', $abbrevs[0], $abbrevs[1], count($abbrevs) > 2 ? sprintf(' and %d more', count($abbrevs) - 2) : '');
1000     }
1001
1002     /**
1003      * Returns the namespace part of the command name.
1004      *
1005      * @param string $name  The full name of the command
1006      * @param string $limit The maximum number of parts of the namespace
1007      *
1008      * @return string The namespace of the command
1009      */
1010     private function extractNamespace($name, $limit = null)
1011     {
1012         $parts = explode(':', $name);
1013         array_pop($parts);
1014
1015         return implode(':', null === $limit ? $parts : array_slice($parts, 0, $limit));
1016     }
1017
1018     /**
1019      * Finds alternative commands of $name
1020      *
1021      * @param string $name    The full name of the command
1022      * @param array  $abbrevs The abbreviations
1023      *
1024      * @return array A sorted array of similar commands
1025      */
1026     private function findAlternativeCommands($name, $abbrevs)
1027     {
1028         $callback = function($item) {
1029             return $item->getName();
1030         };
1031
1032         return $this->findAlternatives($name, $this->commands, $abbrevs, $callback);
1033     }
1034
1035     /**
1036      * Finds alternative namespace of $name
1037      *
1038      * @param string $name    The full name of the namespace
1039      * @param array  $abbrevs The abbreviations
1040      *
1041      * @return array A sorted array of similar namespace
1042      */
1043     private function findAlternativeNamespace($name, $abbrevs)
1044     {
1045         return $this->findAlternatives($name, $this->getNamespaces(), $abbrevs);
1046     }
1047
1048     /**
1049      * Finds alternative of $name among $collection,
1050      * if nothing is found in $collection, try in $abbrevs
1051      *
1052      * @param string               $name       The string
1053      * @param array|Traversable    $collection The collection
1054      * @param array                $abbrevs    The abbreviations
1055      * @param Closure|string|array $callback   The callable to transform collection item before comparison
1056      *
1057      * @return array A sorted array of similar string
1058      */
1059     private function findAlternatives($name, $collection, $abbrevs, $callback = null)
1060     {
1061         $alternatives = array();
1062
1063         foreach ($collection as $item) {
1064             if (null !== $callback) {
1065                 $item = call_user_func($callback, $item);
1066             }
1067
1068             $lev = levenshtein($name, $item);
1069             if ($lev <= strlen($name) / 3 || false !== strpos($item, $name)) {
1070                 $alternatives[$item] = $lev;
1071             }
1072         }
1073
1074         if (!$alternatives) {
1075             foreach ($abbrevs as $key => $values) {
1076                 $lev = levenshtein($name, $key);
1077                 if ($lev <= strlen($name) / 3 || false !== strpos($key, $name)) {
1078                     foreach ($values as $value) {
1079                         $alternatives[$value] = $lev;
1080                     }
1081                 }
1082             }
1083         }
1084
1085         asort($alternatives);
1086
1087         return array_keys($alternatives);
1088     }
1089 }