Application.php 48 KB

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