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