PageRenderTime 364ms CodeModel.GetById 183ms app.highlight 86ms RepoModel.GetById 83ms app.codeStats 1ms

/wwwroot/phpbb/vendor/symfony/console/Symfony/Component/Console/Application.php

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