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