Aucune description

Application.php 36KB

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