Application.php 42 KB

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