Application.php 40 KB

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