Completed
Branch development (b1b115)
by Johannes
10:28
created

Application::run()   F

Complexity

Conditions 22
Paths 4320

Size

Total Lines 81

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 81
rs 0
cc 22
nc 4320
nop 2

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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