Application.php 40 KB

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