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