MIOLO20
Carregando...
Procurando...
Nenhuma entrada encontrada
Application.php
Ir para a documentação deste ficheiro.
1<?php
2
4
20
21/*
22 * This file is part of the Symfony framework.
23 *
24 * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
25 *
26 * This source file is subject to the MIT license that is bundled
27 * with this source code in the file LICENSE.
28 */
29
46{
47 protected $commands;
48 protected $aliases;
49 protected $wantHelps = false;
50 protected $runningCommand;
51 protected $name;
52 protected $version;
54 protected $autoExit;
55 protected $definition;
56 protected $helperSet;
57
64 public function __construct($name = 'UNKNOWN', $version = 'UNKNOWN')
65 {
66 $this->name = $name;
67 $this->version = $version;
68 $this->catchExceptions = true;
69 $this->autoExit = true;
70 $this->commands = array();
71 $this->aliases = array();
72 $this->helperSet = new HelperSet(array(
73 new FormatterHelper(),
74 new DialogHelper(),
75 ));
76
77 $this->add(new HelpCommand());
78 $this->add(new ListCommand());
79
80 $this->definition = new InputDefinition(array(
81 new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'),
82
83 new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message.'),
84 new InputOption('--quiet', '-q', InputOption::VALUE_NONE, 'Do not output any message.'),
85 new InputOption('--verbose', '-v', InputOption::VALUE_NONE, 'Increase verbosity of messages.'),
86 new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display this program version.'),
87 new InputOption('--ansi', '-a', InputOption::VALUE_NONE, 'Force ANSI output.'),
88 new InputOption('--no-interaction', '-n', InputOption::VALUE_NONE, 'Do not ask any interactive question.'),
89 ));
90 }
91
102 public function run(InputInterface $input = null, OutputInterface $output = null)
103 {
104 if (null === $input) {
105 $input = new ArgvInput();
106 }
107
108 if (null === $output) {
109 $output = new ConsoleOutput();
110 }
111
112 try {
113 $statusCode = $this->doRun($input, $output);
114 } catch (\Exception $e) {
115 if (!$this->catchExceptions) {
116 throw $e;
117 }
118
119 $this->renderException($e, $output);
120 $statusCode = $e->getCode();
121
122 $statusCode = is_numeric($statusCode) && $statusCode ? $statusCode : 1;
123 }
124
125 if ($this->autoExit) {
126 if ($statusCode > 255) {
127 $statusCode = 255;
128 }
129 // @codeCoverageIgnoreStart
130 exit($statusCode);
131 // @codeCoverageIgnoreEnd
132 } else {
133 return $statusCode;
134 }
135 }
136
145 public function doRun(InputInterface $input, OutputInterface $output)
146 {
147 $name = $this->getCommandName($input);
148
149 if (true === $input->hasParameterOption(array('--ansi', '-a'))) {
150 $output->setDecorated(true);
151 }
152
153 if (true === $input->hasParameterOption(array('--help', '-h'))) {
154 if (!$name) {
155 $name = 'help';
156 $input = new ArrayInput(array('command' => 'help'));
157 } else {
158 $this->wantHelps = true;
159 }
160 }
161
162 if (true === $input->hasParameterOption(array('--no-interaction', '-n'))) {
163 $input->setInteractive(false);
164 }
165
166 if (true === $input->hasParameterOption(array('--quiet', '-q'))) {
167 $output->setVerbosity(Output::VERBOSITY_QUIET);
168 } elseif (true === $input->hasParameterOption(array('--verbose', '-v'))) {
169 $output->setVerbosity(Output::VERBOSITY_VERBOSE);
170 }
171
172 if (true === $input->hasParameterOption(array('--version', '-V'))) {
173 $output->writeln($this->getLongVersion());
174
175 return 0;
176 }
177
178 if (!$name) {
179 $name = 'list';
180 $input = new ArrayInput(array('command' => 'list'));
181 }
182
183 // the command name MUST be the first element of the input
184 $command = $this->find($name);
185
186 $this->runningCommand = $command;
187 $statusCode = $command->run($input, $output);
188 $this->runningCommand = null;
189
190 return is_numeric($statusCode) ? $statusCode : 0;
191 }
192
199 {
200 $this->helperSet = $helperSet;
201 }
202
208 public function getHelperSet()
209 {
210 return $this->helperSet;
211 }
212
218 public function getDefinition()
219 {
220 return $this->definition;
221 }
222
228 public function getHelp()
229 {
230 $messages = array(
231 $this->getLongVersion(),
232 '',
233 '<comment>Usage:</comment>',
234 sprintf(" [options] command [arguments]\n"),
235 '<comment>Options:</comment>',
236 );
237
238 foreach ($this->definition->getOptions() as $option) {
239 $messages[] = sprintf(' %-29s %s %s',
240 '<info>--'.$option->getName().'</info>',
241 $option->getShortcut() ? '<info>-'.$option->getShortcut().'</info>' : ' ',
242 $option->getDescription()
243 );
244 }
245
246 return implode("\n", $messages);
247 }
248
254 public function setCatchExceptions($boolean)
255 {
256 $this->catchExceptions = (Boolean) $boolean;
257 }
258
264 public function setAutoExit($boolean)
265 {
266 $this->autoExit = (Boolean) $boolean;
267 }
268
274 public function getName()
275 {
276 return $this->name;
277 }
278
284 public function setName($name)
285 {
286 $this->name = $name;
287 }
288
294 public function getVersion()
295 {
296 return $this->version;
297 }
298
304 public function setVersion($version)
305 {
306 $this->version = $version;
307 }
308
314 public function getLongVersion()
315 {
316 if ('UNKNOWN' !== $this->getName() && 'UNKNOWN' !== $this->getVersion()) {
317 return sprintf('<info>%s</info> version <comment>%s</comment>', $this->getName(), $this->getVersion());
318 } else {
319 return '<info>Console Tool</info>';
320 }
321 }
322
330 public function register($name)
331 {
332 return $this->add(new Command($name));
333 }
334
340 public function addCommands(array $commands)
341 {
342 foreach ($commands as $command) {
343 $this->add($command);
344 }
345 }
346
356 public function add(Command $command)
357 {
358 $command->setApplication($this);
359
360 $this->commands[$command->getFullName()] = $command;
361
362 foreach ($command->getAliases() as $alias) {
363 $this->aliases[$alias] = $command;
364 }
365
366 return $command;
367 }
368
378 public function get($name)
379 {
380 if (!isset($this->commands[$name]) && !isset($this->aliases[$name])) {
381 throw new \InvalidArgumentException(sprintf('The command "%s" does not exist.', $name));
382 }
383
384 $command = isset($this->commands[$name]) ? $this->commands[$name] : $this->aliases[$name];
385
386 if ($this->wantHelps) {
387 $this->wantHelps = false;
388
389 $helpCommand = $this->get('help');
390 $helpCommand->setCommand($command);
391
392 return $helpCommand;
393 }
394
395 return $command;
396 }
397
405 public function has($name)
406 {
407 return isset($this->commands[$name]) || isset($this->aliases[$name]);
408 }
409
417 public function getNamespaces()
418 {
419 $namespaces = array();
420 foreach ($this->commands as $command) {
421 if ($command->getNamespace()) {
422 $namespaces[$command->getNamespace()] = true;
423 }
424 }
425
426 return array_keys($namespaces);
427 }
428
436 public function findNamespace($namespace)
437 {
438 $abbrevs = static::getAbbreviations($this->getNamespaces());
439
440 if (!isset($abbrevs[$namespace])) {
441 throw new \InvalidArgumentException(sprintf('There are no commands defined in the "%s" namespace.', $namespace));
442 }
443
444 if (count($abbrevs[$namespace]) > 1) {
445 throw new \InvalidArgumentException(sprintf('The namespace "%s" is ambiguous (%s).', $namespace, $this->getAbbreviationSuggestions($abbrevs[$namespace])));
446 }
447
448 return $abbrevs[$namespace][0];
449 }
450
463 public function find($name)
464 {
465 // namespace
466 $namespace = '';
467 if (false !== $pos = strrpos($name, ':')) {
468 $namespace = $this->findNamespace(substr($name, 0, $pos));
469 $name = substr($name, $pos + 1);
470 }
471
472 $fullName = $namespace ? $namespace.':'.$name : $name;
473
474 // name
475 $commands = array();
476 foreach ($this->commands as $command) {
477 if ($command->getNamespace() == $namespace) {
478 $commands[] = $command->getName();
479 }
480 }
481
482 $abbrevs = static::getAbbreviations($commands);
483 if (isset($abbrevs[$name]) && 1 == count($abbrevs[$name])) {
484 return $this->get($namespace ? $namespace.':'.$abbrevs[$name][0] : $abbrevs[$name][0]);
485 }
486
487 if (isset($abbrevs[$name]) && count($abbrevs[$name]) > 1) {
488 $suggestions = $this->getAbbreviationSuggestions(array_map(function ($command) use ($namespace) { return $namespace.':'.$command; }, $abbrevs[$name]));
489
490 throw new \InvalidArgumentException(sprintf('Command "%s" is ambiguous (%s).', $fullName, $suggestions));
491 }
492
493 // aliases
494 $abbrevs = static::getAbbreviations(array_keys($this->aliases));
495 if (!isset($abbrevs[$fullName])) {
496 throw new \InvalidArgumentException(sprintf('Command "%s" is not defined.', $fullName));
497 }
498
499 if (count($abbrevs[$fullName]) > 1) {
500 throw new \InvalidArgumentException(sprintf('Command "%s" is ambiguous (%s).', $fullName, $this->getAbbreviationSuggestions($abbrevs[$fullName])));
501 }
502
503 return $this->get($abbrevs[$fullName][0]);
504 }
505
515 public function all($namespace = null)
516 {
517 if (null === $namespace) {
518 return $this->commands;
519 }
520
521 $commands = array();
522 foreach ($this->commands as $name => $command) {
523 if ($namespace === $command->getNamespace()) {
524 $commands[$name] = $command;
525 }
526 }
527
528 return $commands;
529 }
530
538 static public function getAbbreviations($names)
539 {
540 $abbrevs = array();
541 foreach ($names as $name) {
542 for ($len = strlen($name) - 1; $len > 0; --$len) {
543 $abbrev = substr($name, 0, $len);
544 if (!isset($abbrevs[$abbrev])) {
545 $abbrevs[$abbrev] = array($name);
546 } else {
547 $abbrevs[$abbrev][] = $name;
548 }
549 }
550 }
551
552 // Non-abbreviations always get entered, even if they aren't unique
553 foreach ($names as $name) {
554 $abbrevs[$name] = array($name);
555 }
556
557 return $abbrevs;
558 }
559
567 public function asText($namespace = null)
568 {
569 $commands = $namespace ? $this->all($this->findNamespace($namespace)) : $this->commands;
570
571 $messages = array($this->getHelp(), '');
572 if ($namespace) {
573 $messages[] = sprintf("<comment>Available commands for the \"%s\" namespace:</comment>", $namespace);
574 } else {
575 $messages[] = '<comment>Available commands:</comment>';
576 }
577
578 $width = 0;
579 foreach ($commands as $command) {
580 $width = strlen($command->getName()) > $width ? strlen($command->getName()) : $width;
581 }
582 $width += 2;
583
584 // add commands by namespace
585 foreach ($this->sortCommands($commands) as $space => $commands) {
586 if (!$namespace && '_global' !== $space) {
587 $messages[] = '<comment>'.$space.'</comment>';
588 }
589
590 foreach ($commands as $command) {
591 $aliases = $command->getAliases() ? '<comment> ('.implode(', ', $command->getAliases()).')</comment>' : '';
592
593 $messages[] = sprintf(" <info>%-${width}s</info> %s%s", ($command->getNamespace() ? ':' : '').$command->getName(), $command->getDescription(), $aliases);
594 }
595 }
596
597 return implode("\n", $messages);
598 }
599
608 public function asXml($namespace = null, $asDom = false)
609 {
610 $commands = $namespace ? $this->all($this->findNamespace($namespace)) : $this->commands;
611
612 $dom = new \DOMDocument('1.0', 'UTF-8');
613 $dom->formatOutput = true;
614 $dom->appendChild($xml = $dom->createElement('symfony'));
615
616 $xml->appendChild($commandsXML = $dom->createElement('commands'));
617
618 if ($namespace) {
619 $commandsXML->setAttribute('namespace', $namespace);
620 } else {
621 $xml->appendChild($namespacesXML = $dom->createElement('namespaces'));
622 }
623
624 // add commands by namespace
625 foreach ($this->sortCommands($commands) as $space => $commands) {
626 if (!$namespace) {
627 $namespacesXML->appendChild($namespaceArrayXML = $dom->createElement('namespace'));
628 $namespaceArrayXML->setAttribute('id', $space);
629 }
630
631 foreach ($commands as $command) {
632 if (!$namespace) {
633 $namespaceArrayXML->appendChild($commandXML = $dom->createElement('command'));
634 $commandXML->appendChild($dom->createTextNode($command->getName()));
635 }
636
637 $node = $command->asXml(true)->getElementsByTagName('command')->item(0);
638 $node = $dom->importNode($node, true);
639
640 $commandsXML->appendChild($node);
641 }
642 }
643
644 return $asDom ? $dom : $dom->saveXml();
645 }
646
653 public function renderException($e, $output)
654 {
655 $strlen = function ($string)
656 {
657 return function_exists('mb_strlen') ? mb_strlen($string) : strlen($string);
658 };
659
660 $title = sprintf(' [%s] ', get_class($e));
661 $len = $strlen($title);
662 $lines = array();
663 foreach (explode("\n", $e->getMessage()) as $line) {
664 $lines[] = sprintf(' %s ', $line);
665 $len = max($strlen($line) + 4, $len);
666 }
667
668 $messages = array(str_repeat(' ', $len), $title.str_repeat(' ', $len - $strlen($title)));
669
670 foreach ($lines as $line) {
671 $messages[] = $line.str_repeat(' ', $len - $strlen($line));
672 }
673
674 $messages[] = str_repeat(' ', $len);
675
676 $output->writeln("\n");
677 foreach ($messages as $message) {
678 $output->writeln('<error>'.$message.'</error>');
679 }
680 $output->writeln("\n");
681
682 if (null !== $this->runningCommand) {
683 $output->writeln(sprintf('<info>%s</info>', sprintf($this->runningCommand->getSynopsis(), $this->getName())));
684 $output->writeln("\n");
685 }
686
687 if (Output::VERBOSITY_VERBOSE === $output->getVerbosity()) {
688 $output->writeln('</comment>Exception trace:</comment>');
689
690 // exception related properties
691 $trace = $e->getTrace();
692 array_unshift($trace, array(
693 'function' => '',
694 'file' => $e->getFile() != null ? $e->getFile() : 'n/a',
695 'line' => $e->getLine() != null ? $e->getLine() : 'n/a',
696 'args' => array(),
697 ));
698
699 for ($i = 0, $count = count($trace); $i < $count; $i++) {
700 $class = isset($trace[$i]['class']) ? $trace[$i]['class'] : '';
701 $type = isset($trace[$i]['type']) ? $trace[$i]['type'] : '';
702 $function = $trace[$i]['function'];
703 $file = isset($trace[$i]['file']) ? $trace[$i]['file'] : 'n/a';
704 $line = isset($trace[$i]['line']) ? $trace[$i]['line'] : 'n/a';
705
706 $output->writeln(sprintf(' %s%s%s() at <info>%s:%s</info>', $class, $type, $function, $file, $line));
707 }
708
709 $output->writeln("\n");
710 }
711 }
712
713 protected function getCommandName(InputInterface $input)
714 {
715 return $input->getFirstArgument('command');
716 }
717
718 protected function sortCommands($commands)
719 {
720 $namespacedCommands = array();
721 foreach ($commands as $name => $command) {
722 $key = $command->getNamespace() ? $command->getNamespace() : '_global';
723
724 if (!isset($namespacedCommands[$key])) {
725 $namespacedCommands[$key] = array();
726 }
727
728 $namespacedCommands[$key][$name] = $command;
729 }
730 ksort($namespacedCommands);
731
732 foreach ($namespacedCommands as $name => &$commands) {
733 ksort($commands);
734 }
735
736 return $namespacedCommands;
737 }
738
739 protected function getAbbreviationSuggestions($abbrevs)
740 {
741 return sprintf('%s, %s%s', $abbrevs[0], $abbrevs[1], count($abbrevs) > 2 ? sprintf(' and %d more', count($abbrevs) - 2) : '');
742 }
743}
run(InputInterface $input=null, OutputInterface $output=null)
doRun(InputInterface $input, OutputInterface $output)
getCommandName(InputInterface $input)
__construct($name='UNKNOWN', $version='UNKNOWN')
Definição Application.php:64
asXml($namespace=null, $asDom=false)
setHelperSet(HelperSet $helperSet)
setApplication(Application $application=null)
Definição Command.php:69
$title
Definição base.php:3