ConsoleOptionParser.php 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 2.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Console;
  16. use Cake\Console\Exception\ConsoleException;
  17. use Cake\Utility\Inflector;
  18. use LogicException;
  19. /**
  20. * Handles parsing the ARGV in the command line and provides support
  21. * for GetOpt compatible option definition. Provides a builder pattern implementation
  22. * for creating shell option parsers.
  23. *
  24. * ### Options
  25. *
  26. * Named arguments come in two forms, long and short. Long arguments are preceded
  27. * by two - and give a more verbose option name. i.e. `--version`. Short arguments are
  28. * preceded by one - and are only one character long. They usually match with a long option,
  29. * and provide a more terse alternative.
  30. *
  31. * ### Using Options
  32. *
  33. * Options can be defined with both long and short forms. By using `$parser->addOption()`
  34. * you can define new options. The name of the option is used as its long form, and you
  35. * can supply an additional short form, with the `short` option. Short options should
  36. * only be one letter long. Using more than one letter for a short option will raise an exception.
  37. *
  38. * Calling options can be done using syntax similar to most *nix command line tools. Long options
  39. * cane either include an `=` or leave it out.
  40. *
  41. * `cake myshell command --connection default --name=something`
  42. *
  43. * Short options can be defined singly or in groups.
  44. *
  45. * `cake myshell command -cn`
  46. *
  47. * Short options can be combined into groups as seen above. Each letter in a group
  48. * will be treated as a separate option. The previous example is equivalent to:
  49. *
  50. * `cake myshell command -c -n`
  51. *
  52. * Short options can also accept values:
  53. *
  54. * `cake myshell command -c default`
  55. *
  56. * ### Positional arguments
  57. *
  58. * If no positional arguments are defined, all of them will be parsed. If you define positional
  59. * arguments any arguments greater than those defined will cause exceptions. Additionally you can
  60. * declare arguments as optional, by setting the required param to false.
  61. *
  62. * ```
  63. * $parser->addArgument('model', ['required' => false]);
  64. * ```
  65. *
  66. * ### Providing Help text
  67. *
  68. * By providing help text for your positional arguments and named arguments, the ConsoleOptionParser
  69. * can generate a help display for you. You can view the help for shells by using the `--help` or `-h` switch.
  70. */
  71. class ConsoleOptionParser
  72. {
  73. /**
  74. * Description text - displays before options when help is generated
  75. *
  76. * @see \Cake\Console\ConsoleOptionParser::description()
  77. * @var string
  78. */
  79. protected $_description;
  80. /**
  81. * Epilog text - displays after options when help is generated
  82. *
  83. * @see \Cake\Console\ConsoleOptionParser::epilog()
  84. * @var string
  85. */
  86. protected $_epilog;
  87. /**
  88. * Option definitions.
  89. *
  90. * @see \Cake\Console\ConsoleOptionParser::addOption()
  91. * @var \Cake\Console\ConsoleInputOption[]
  92. */
  93. protected $_options = [];
  94. /**
  95. * Map of short -> long options, generated when using addOption()
  96. *
  97. * @var array
  98. */
  99. protected $_shortOptions = [];
  100. /**
  101. * Positional argument definitions.
  102. *
  103. * @see \Cake\Console\ConsoleOptionParser::addArgument()
  104. * @var \Cake\Console\ConsoleInputArgument[]
  105. */
  106. protected $_args = [];
  107. /**
  108. * Subcommands for this Shell.
  109. *
  110. * @see \Cake\Console\ConsoleOptionParser::addSubcommand()
  111. * @var \Cake\Console\ConsoleInputSubcommand[]
  112. */
  113. protected $_subcommands = [];
  114. /**
  115. * Command name.
  116. *
  117. * @var string
  118. */
  119. protected $_command = '';
  120. /**
  121. * Array of args (argv).
  122. *
  123. * @var array
  124. */
  125. protected $_tokens = [];
  126. /**
  127. * Root alias used in help output
  128. *
  129. * @see \Cake\Console\HelpFormatter::setAlias()
  130. * @var string
  131. */
  132. protected $rootName = 'cake';
  133. /**
  134. * Construct an OptionParser so you can define its behavior
  135. *
  136. * @param string|null $command The command name this parser is for. The command name is used for generating help.
  137. * @param bool $defaultOptions Whether you want the verbose and quiet options set. Setting
  138. * this to false will prevent the addition of `--verbose` & `--quiet` options.
  139. */
  140. public function __construct($command = null, $defaultOptions = true)
  141. {
  142. $this->setCommand($command);
  143. $this->addOption('help', [
  144. 'short' => 'h',
  145. 'help' => 'Display this help.',
  146. 'boolean' => true
  147. ]);
  148. if ($defaultOptions) {
  149. $this->addOption('verbose', [
  150. 'short' => 'v',
  151. 'help' => 'Enable verbose output.',
  152. 'boolean' => true
  153. ])->addOption('quiet', [
  154. 'short' => 'q',
  155. 'help' => 'Enable quiet output.',
  156. 'boolean' => true
  157. ]);
  158. }
  159. }
  160. /**
  161. * Static factory method for creating new OptionParsers so you can chain methods off of them.
  162. *
  163. * @param string|null $command The command name this parser is for. The command name is used for generating help.
  164. * @param bool $defaultOptions Whether you want the verbose and quiet options set.
  165. * @return static
  166. */
  167. public static function create($command, $defaultOptions = true)
  168. {
  169. return new static($command, $defaultOptions);
  170. }
  171. /**
  172. * Build a parser from an array. Uses an array like
  173. *
  174. * ```
  175. * $spec = [
  176. * 'description' => 'text',
  177. * 'epilog' => 'text',
  178. * 'arguments' => [
  179. * // list of arguments compatible with addArguments.
  180. * ],
  181. * 'options' => [
  182. * // list of options compatible with addOptions
  183. * ],
  184. * 'subcommands' => [
  185. * // list of subcommands to add.
  186. * ]
  187. * ];
  188. * ```
  189. *
  190. * @param array $spec The spec to build the OptionParser with.
  191. * @param bool $defaultOptions Whether you want the verbose and quiet options set.
  192. * @return static
  193. */
  194. public static function buildFromArray($spec, $defaultOptions = true)
  195. {
  196. $parser = new static($spec['command'], $defaultOptions);
  197. if (!empty($spec['arguments'])) {
  198. $parser->addArguments($spec['arguments']);
  199. }
  200. if (!empty($spec['options'])) {
  201. $parser->addOptions($spec['options']);
  202. }
  203. if (!empty($spec['subcommands'])) {
  204. $parser->addSubcommands($spec['subcommands']);
  205. }
  206. if (!empty($spec['description'])) {
  207. $parser->setDescription($spec['description']);
  208. }
  209. if (!empty($spec['epilog'])) {
  210. $parser->setEpilog($spec['epilog']);
  211. }
  212. return $parser;
  213. }
  214. /**
  215. * Returns an array representation of this parser.
  216. *
  217. * @return array
  218. */
  219. public function toArray()
  220. {
  221. $result = [
  222. 'command' => $this->_command,
  223. 'arguments' => $this->_args,
  224. 'options' => $this->_options,
  225. 'subcommands' => $this->_subcommands,
  226. 'description' => $this->_description,
  227. 'epilog' => $this->_epilog
  228. ];
  229. return $result;
  230. }
  231. /**
  232. * Get or set the command name for shell/task.
  233. *
  234. * @param array|\Cake\Console\ConsoleOptionParser $spec ConsoleOptionParser or spec to merge with.
  235. * @return $this
  236. */
  237. public function merge($spec)
  238. {
  239. if ($spec instanceof ConsoleOptionParser) {
  240. $spec = $spec->toArray();
  241. }
  242. if (!empty($spec['arguments'])) {
  243. $this->addArguments($spec['arguments']);
  244. }
  245. if (!empty($spec['options'])) {
  246. $this->addOptions($spec['options']);
  247. }
  248. if (!empty($spec['subcommands'])) {
  249. $this->addSubcommands($spec['subcommands']);
  250. }
  251. if (!empty($spec['description'])) {
  252. $this->setDescription($spec['description']);
  253. }
  254. if (!empty($spec['epilog'])) {
  255. $this->setEpilog($spec['epilog']);
  256. }
  257. return $this;
  258. }
  259. /**
  260. * Sets the command name for shell/task.
  261. *
  262. * @param string $text The text to set.
  263. * @return $this
  264. */
  265. public function setCommand($text)
  266. {
  267. $this->_command = Inflector::underscore($text);
  268. return $this;
  269. }
  270. /**
  271. * Gets the command name for shell/task.
  272. *
  273. * @return string The value of the command.
  274. */
  275. public function getCommand()
  276. {
  277. return $this->_command;
  278. }
  279. /**
  280. * Gets or sets the command name for shell/task.
  281. *
  282. * @deprecated 3.4.0 Use setCommand()/getCommand() instead.
  283. * @param string|null $text The text to set, or null if you want to read
  284. * @return string|$this If reading, the value of the command. If setting $this will be returned.
  285. */
  286. public function command($text = null)
  287. {
  288. if ($text !== null) {
  289. return $this->setCommand($text);
  290. }
  291. return $this->getCommand();
  292. }
  293. /**
  294. * Sets the description text for shell/task.
  295. *
  296. * @param string|array $text The text to set. If an array the
  297. * text will be imploded with "\n".
  298. * @return $this
  299. */
  300. public function setDescription($text)
  301. {
  302. if (is_array($text)) {
  303. $text = implode("\n", $text);
  304. }
  305. $this->_description = $text;
  306. return $this;
  307. }
  308. /**
  309. * Gets the description text for shell/task.
  310. *
  311. * @return string The value of the description
  312. */
  313. public function getDescription()
  314. {
  315. return $this->_description;
  316. }
  317. /**
  318. * Get or set the description text for shell/task.
  319. *
  320. * @deprecated 3.4.0 Use setDescription()/getDescription() instead.
  321. * @param string|array|null $text The text to set, or null if you want to read. If an array the
  322. * text will be imploded with "\n".
  323. * @return string|$this If reading, the value of the description. If setting $this will be returned.
  324. */
  325. public function description($text = null)
  326. {
  327. if ($text !== null) {
  328. return $this->setDescription($text);
  329. }
  330. return $this->getDescription();
  331. }
  332. /**
  333. * Sets an epilog to the parser. The epilog is added to the end of
  334. * the options and arguments listing when help is generated.
  335. *
  336. * @param string|array $text The text to set. If an array the text will
  337. * be imploded with "\n".
  338. * @return $this
  339. */
  340. public function setEpilog($text)
  341. {
  342. if (is_array($text)) {
  343. $text = implode("\n", $text);
  344. }
  345. $this->_epilog = $text;
  346. return $this;
  347. }
  348. /**
  349. * Gets the epilog.
  350. *
  351. * @return string The value of the epilog.
  352. */
  353. public function getEpilog()
  354. {
  355. return $this->_epilog;
  356. }
  357. /**
  358. * Gets or sets an epilog to the parser. The epilog is added to the end of
  359. * the options and arguments listing when help is generated.
  360. *
  361. * @deprecated 3.4.0 Use setEpilog()/getEpilog() instead.
  362. * @param string|array|null $text Text when setting or null when reading. If an array the text will
  363. * be imploded with "\n".
  364. * @return string|$this If reading, the value of the epilog. If setting $this will be returned.
  365. */
  366. public function epilog($text = null)
  367. {
  368. if ($text !== null) {
  369. return $this->setEpilog($text);
  370. }
  371. return $this->getEpilog();
  372. }
  373. /**
  374. * Add an option to the option parser. Options allow you to define optional or required
  375. * parameters for your console application. Options are defined by the parameters they use.
  376. *
  377. * ### Options
  378. *
  379. * - `short` - The single letter variant for this option, leave undefined for none.
  380. * - `help` - Help text for this option. Used when generating help for the option.
  381. * - `default` - The default value for this option. Defaults are added into the parsed params when the
  382. * attached option is not provided or has no value. Using default and boolean together will not work.
  383. * are added into the parsed parameters when the option is undefined. Defaults to null.
  384. * - `boolean` - The option uses no value, it's just a boolean switch. Defaults to false.
  385. * If an option is defined as boolean, it will always be added to the parsed params. If no present
  386. * it will be false, if present it will be true.
  387. * - `multiple` - The option can be provided multiple times. The parsed option
  388. * will be an array of values when this option is enabled.
  389. * - `choices` A list of valid choices for this option. If left empty all values are valid..
  390. * An exception will be raised when parse() encounters an invalid value.
  391. *
  392. * @param \Cake\Console\ConsoleInputOption|string $name The long name you want to the value to be parsed out as when options are parsed.
  393. * Will also accept an instance of ConsoleInputOption
  394. * @param array $options An array of parameters that define the behavior of the option
  395. * @return $this
  396. */
  397. public function addOption($name, array $options = [])
  398. {
  399. if ($name instanceof ConsoleInputOption) {
  400. $option = $name;
  401. $name = $option->name();
  402. } else {
  403. $defaults = [
  404. 'name' => $name,
  405. 'short' => null,
  406. 'help' => '',
  407. 'default' => null,
  408. 'boolean' => false,
  409. 'choices' => []
  410. ];
  411. $options += $defaults;
  412. $option = new ConsoleInputOption($options);
  413. }
  414. $this->_options[$name] = $option;
  415. asort($this->_options);
  416. if ($option->short() !== null) {
  417. $this->_shortOptions[$option->short()] = $name;
  418. asort($this->_shortOptions);
  419. }
  420. return $this;
  421. }
  422. /**
  423. * Remove an option from the option parser.
  424. *
  425. * @param string $name The option name to remove.
  426. * @return $this
  427. */
  428. public function removeOption($name)
  429. {
  430. unset($this->_options[$name]);
  431. return $this;
  432. }
  433. /**
  434. * Add a positional argument to the option parser.
  435. *
  436. * ### Params
  437. *
  438. * - `help` The help text to display for this argument.
  439. * - `required` Whether this parameter is required.
  440. * - `index` The index for the arg, if left undefined the argument will be put
  441. * onto the end of the arguments. If you define the same index twice the first
  442. * option will be overwritten.
  443. * - `choices` A list of valid choices for this argument. If left empty all values are valid..
  444. * An exception will be raised when parse() encounters an invalid value.
  445. *
  446. * @param \Cake\Console\ConsoleInputArgument|string $name The name of the argument.
  447. * Will also accept an instance of ConsoleInputArgument.
  448. * @param array $params Parameters for the argument, see above.
  449. * @return $this
  450. */
  451. public function addArgument($name, array $params = [])
  452. {
  453. if ($name instanceof ConsoleInputArgument) {
  454. $arg = $name;
  455. $index = count($this->_args);
  456. } else {
  457. $defaults = [
  458. 'name' => $name,
  459. 'help' => '',
  460. 'index' => count($this->_args),
  461. 'required' => false,
  462. 'choices' => []
  463. ];
  464. $options = $params + $defaults;
  465. $index = $options['index'];
  466. unset($options['index']);
  467. $arg = new ConsoleInputArgument($options);
  468. }
  469. foreach ($this->_args as $k => $a) {
  470. if ($a->isEqualTo($arg)) {
  471. return $this;
  472. }
  473. if (!empty($options['required']) && !$a->isRequired()) {
  474. throw new LogicException('A required argument cannot follow an optional one');
  475. }
  476. }
  477. $this->_args[$index] = $arg;
  478. ksort($this->_args);
  479. return $this;
  480. }
  481. /**
  482. * Add multiple arguments at once. Take an array of argument definitions.
  483. * The keys are used as the argument names, and the values as params for the argument.
  484. *
  485. * @param array $args Array of arguments to add.
  486. * @see \Cake\Console\ConsoleOptionParser::addArgument()
  487. * @return $this
  488. */
  489. public function addArguments(array $args)
  490. {
  491. foreach ($args as $name => $params) {
  492. if ($params instanceof ConsoleInputArgument) {
  493. $name = $params;
  494. $params = [];
  495. }
  496. $this->addArgument($name, $params);
  497. }
  498. return $this;
  499. }
  500. /**
  501. * Add multiple options at once. Takes an array of option definitions.
  502. * The keys are used as option names, and the values as params for the option.
  503. *
  504. * @param array $options Array of options to add.
  505. * @see \Cake\Console\ConsoleOptionParser::addOption()
  506. * @return $this
  507. */
  508. public function addOptions(array $options)
  509. {
  510. foreach ($options as $name => $params) {
  511. if ($params instanceof ConsoleInputOption) {
  512. $name = $params;
  513. $params = [];
  514. }
  515. $this->addOption($name, $params);
  516. }
  517. return $this;
  518. }
  519. /**
  520. * Append a subcommand to the subcommand list.
  521. * Subcommands are usually methods on your Shell, but can also be used to document Tasks.
  522. *
  523. * ### Options
  524. *
  525. * - `help` - Help text for the subcommand.
  526. * - `parser` - A ConsoleOptionParser for the subcommand. This allows you to create method
  527. * specific option parsers. When help is generated for a subcommand, if a parser is present
  528. * it will be used.
  529. *
  530. * @param \Cake\Console\ConsoleInputSubcommand|string $name Name of the subcommand. Will also accept an instance of ConsoleInputSubcommand
  531. * @param array $options Array of params, see above.
  532. * @return $this
  533. */
  534. public function addSubcommand($name, array $options = [])
  535. {
  536. if ($name instanceof ConsoleInputSubcommand) {
  537. $command = $name;
  538. $name = $command->name();
  539. } else {
  540. $name = Inflector::underscore($name);
  541. $defaults = [
  542. 'name' => $name,
  543. 'help' => '',
  544. 'parser' => null
  545. ];
  546. $options += $defaults;
  547. $command = new ConsoleInputSubcommand($options);
  548. }
  549. $this->_subcommands[$name] = $command;
  550. asort($this->_subcommands);
  551. return $this;
  552. }
  553. /**
  554. * Remove a subcommand from the option parser.
  555. *
  556. * @param string $name The subcommand name to remove.
  557. * @return $this
  558. */
  559. public function removeSubcommand($name)
  560. {
  561. unset($this->_subcommands[$name]);
  562. return $this;
  563. }
  564. /**
  565. * Add multiple subcommands at once.
  566. *
  567. * @param array $commands Array of subcommands.
  568. * @return $this
  569. */
  570. public function addSubcommands(array $commands)
  571. {
  572. foreach ($commands as $name => $params) {
  573. if ($params instanceof ConsoleInputSubcommand) {
  574. $name = $params;
  575. $params = [];
  576. }
  577. $this->addSubcommand($name, $params);
  578. }
  579. return $this;
  580. }
  581. /**
  582. * Gets the arguments defined in the parser.
  583. *
  584. * @return array Array of argument descriptions
  585. */
  586. public function arguments()
  587. {
  588. return $this->_args;
  589. }
  590. /**
  591. * Get the defined options in the parser.
  592. *
  593. * @return array
  594. */
  595. public function options()
  596. {
  597. return $this->_options;
  598. }
  599. /**
  600. * Get the array of defined subcommands
  601. *
  602. * @return array
  603. */
  604. public function subcommands()
  605. {
  606. return $this->_subcommands;
  607. }
  608. /**
  609. * Parse the argv array into a set of params and args. If $command is not null
  610. * and $command is equal to a subcommand that has a parser, that parser will be used
  611. * to parse the $argv
  612. *
  613. * @param array $argv Array of args (argv) to parse.
  614. * @return array [$params, $args]
  615. * @throws \Cake\Console\Exception\ConsoleException When an invalid parameter is encountered.
  616. */
  617. public function parse($argv)
  618. {
  619. $command = isset($argv[0]) ? Inflector::underscore($argv[0]) : null;
  620. if (isset($this->_subcommands[$command])) {
  621. array_shift($argv);
  622. }
  623. if (isset($this->_subcommands[$command]) && $this->_subcommands[$command]->parser()) {
  624. return $this->_subcommands[$command]->parser()->parse($argv);
  625. }
  626. $params = $args = [];
  627. $this->_tokens = $argv;
  628. while (($token = array_shift($this->_tokens)) !== null) {
  629. if (isset($this->_subcommands[$token])) {
  630. continue;
  631. }
  632. if (substr($token, 0, 2) === '--') {
  633. $params = $this->_parseLongOption($token, $params);
  634. } elseif (substr($token, 0, 1) === '-') {
  635. $params = $this->_parseShortOption($token, $params);
  636. } else {
  637. $args = $this->_parseArg($token, $args);
  638. }
  639. }
  640. foreach ($this->_args as $i => $arg) {
  641. if ($arg->isRequired() && !isset($args[$i]) && empty($params['help'])) {
  642. throw new ConsoleException(
  643. sprintf('Missing required arguments. %s is required.', $arg->name())
  644. );
  645. }
  646. }
  647. foreach ($this->_options as $option) {
  648. $name = $option->name();
  649. $isBoolean = $option->isBoolean();
  650. $default = $option->defaultValue();
  651. if ($default !== null && !isset($params[$name]) && !$isBoolean) {
  652. $params[$name] = $default;
  653. }
  654. if ($isBoolean && !isset($params[$name])) {
  655. $params[$name] = false;
  656. }
  657. }
  658. return [$params, $args];
  659. }
  660. /**
  661. * Gets formatted help for this parser object.
  662. *
  663. * Generates help text based on the description, options, arguments, subcommands and epilog
  664. * in the parser.
  665. *
  666. * @param string|null $subcommand If present and a valid subcommand that has a linked parser.
  667. * That subcommands help will be shown instead.
  668. * @param string $format Define the output format, can be text or xml
  669. * @param int $width The width to format user content to. Defaults to 72
  670. * @return string Generated help.
  671. */
  672. public function help($subcommand = null, $format = 'text', $width = 72)
  673. {
  674. if (isset($this->_subcommands[$subcommand])) {
  675. $command = $this->_subcommands[$subcommand];
  676. $subparser = $command->parser();
  677. if (!($subparser instanceof self)) {
  678. $subparser = clone $this;
  679. }
  680. if (strlen($subparser->getDescription()) === 0) {
  681. $subparser->setDescription($command->getRawHelp());
  682. }
  683. $subparser->setCommand($this->getCommand() . ' ' . $subcommand);
  684. $subparser->setRootName($this->rootName);
  685. return $subparser->help(null, $format, $width);
  686. }
  687. $formatter = new HelpFormatter($this);
  688. $formatter->setAlias($this->rootName);
  689. if ($format === 'text') {
  690. return $formatter->text($width);
  691. }
  692. if ($format === 'xml') {
  693. return $formatter->xml();
  694. }
  695. }
  696. /**
  697. * Set the alias used in the HelpFormatter
  698. *
  699. * @param string $alias The alias
  700. * @return void
  701. * @deprecated 3.5.0 Use setRootName() instead.
  702. */
  703. public function setHelpAlias($alias)
  704. {
  705. $this->rootName = $alias;
  706. }
  707. /**
  708. * Set the root name used in the HelpFormatter
  709. *
  710. * @param string $name The root command name
  711. * @return $this
  712. */
  713. public function setRootName($name)
  714. {
  715. $this->rootName = (string)$name;
  716. return $this;
  717. }
  718. /**
  719. * Get the message output in the console stating that the command can not be found and tries to guess what the user
  720. * wanted to say. Output a list of available subcommands as well.
  721. *
  722. * @param string $command Unknown command name trying to be dispatched.
  723. * @return string The message to be displayed in the console.
  724. */
  725. public function getCommandError($command)
  726. {
  727. $rootCommand = $this->getCommand();
  728. $subcommands = array_keys((array)$this->subcommands());
  729. $bestGuess = $this->findClosestItem($command, $subcommands);
  730. $out = [];
  731. $out[] = sprintf(
  732. 'Unable to find the `%s %s` subcommand. See `bin/%s %s --help`.',
  733. $rootCommand,
  734. $command,
  735. $this->rootName,
  736. $rootCommand
  737. );
  738. $out[] = '';
  739. if ($bestGuess !== null) {
  740. $out[] = sprintf('Did you mean : `%s %s` ?', $rootCommand, $bestGuess);
  741. $out[] = '';
  742. }
  743. $out[] = sprintf('Available subcommands for the `%s` command are : ', $rootCommand);
  744. $out[] = '';
  745. foreach ($subcommands as $subcommand) {
  746. $out[] = ' - ' . $subcommand;
  747. }
  748. return implode("\n", $out);
  749. }
  750. /**
  751. * Get the message output in the console stating that the option can not be found and tries to guess what the user
  752. * wanted to say. Output a list of available options as well.
  753. *
  754. * @param string $option Unknown option name trying to be used.
  755. * @return string The message to be displayed in the console.
  756. */
  757. protected function getOptionError($option)
  758. {
  759. $availableOptions = array_keys($this->_options);
  760. $bestGuess = $this->findClosestItem($option, $availableOptions);
  761. $out = [];
  762. $out[] = sprintf('Unknown option `%s`.', $option);
  763. $out[] = '';
  764. if ($bestGuess !== null) {
  765. $out[] = sprintf('Did you mean `%s` ?', $bestGuess);
  766. $out[] = '';
  767. }
  768. $out[] = 'Available options are :';
  769. $out[] = '';
  770. foreach ($availableOptions as $availableOption) {
  771. $out[] = ' - ' . $availableOption;
  772. }
  773. return implode("\n", $out);
  774. }
  775. /**
  776. * Tries to guess the item name the user originally wanted using the levenshtein algorithm.
  777. *
  778. * @param string $needle Unknown item (either a subcommand name or an option for instance) trying to be used.
  779. * @param array $haystack List of items available for the type $needle belongs to.
  780. * @return string|null The closest name to the item submitted by the user.
  781. */
  782. protected function findClosestItem($needle, $haystack)
  783. {
  784. $bestGuess = null;
  785. foreach ($haystack as $item) {
  786. if (preg_match('/^' . $needle . '/', $item, $matches)) {
  787. return $item;
  788. }
  789. }
  790. foreach ($haystack as $item) {
  791. if (preg_match('/' . $needle . '/', $item, $matches)) {
  792. return $item;
  793. }
  794. $score = levenshtein($needle, $item);
  795. if (!isset($bestScore) || $score < $bestScore) {
  796. $bestScore = levenshtein($needle, $item);
  797. $bestGuess = $item;
  798. }
  799. }
  800. return $bestGuess;
  801. }
  802. /**
  803. * Parse the value for a long option out of $this->_tokens. Will handle
  804. * options with an `=` in them.
  805. *
  806. * @param string $option The option to parse.
  807. * @param array $params The params to append the parsed value into
  808. * @return array Params with $option added in.
  809. */
  810. protected function _parseLongOption($option, $params)
  811. {
  812. $name = substr($option, 2);
  813. if (strpos($name, '=') !== false) {
  814. list($name, $value) = explode('=', $name, 2);
  815. array_unshift($this->_tokens, $value);
  816. }
  817. return $this->_parseOption($name, $params);
  818. }
  819. /**
  820. * Parse the value for a short option out of $this->_tokens
  821. * If the $option is a combination of multiple shortcuts like -otf
  822. * they will be shifted onto the token stack and parsed individually.
  823. *
  824. * @param string $option The option to parse.
  825. * @param array $params The params to append the parsed value into
  826. * @return array Params with $option added in.
  827. * @throws \Cake\Console\Exception\ConsoleException When unknown short options are encountered.
  828. */
  829. protected function _parseShortOption($option, $params)
  830. {
  831. $key = substr($option, 1);
  832. if (strlen($key) > 1) {
  833. $flags = str_split($key);
  834. $key = $flags[0];
  835. for ($i = 1, $len = count($flags); $i < $len; $i++) {
  836. array_unshift($this->_tokens, '-' . $flags[$i]);
  837. }
  838. }
  839. if (!isset($this->_shortOptions[$key])) {
  840. throw new ConsoleException(sprintf('Unknown short option `%s`', $key));
  841. }
  842. $name = $this->_shortOptions[$key];
  843. return $this->_parseOption($name, $params);
  844. }
  845. /**
  846. * Parse an option by its name index.
  847. *
  848. * @param string $name The name to parse.
  849. * @param array $params The params to append the parsed value into
  850. * @return array Params with $option added in.
  851. * @throws \Cake\Console\Exception\ConsoleException
  852. */
  853. protected function _parseOption($name, $params)
  854. {
  855. if (!isset($this->_options[$name])) {
  856. throw new ConsoleException($this->getOptionError($name));
  857. }
  858. $option = $this->_options[$name];
  859. $isBoolean = $option->isBoolean();
  860. $nextValue = $this->_nextToken();
  861. $emptyNextValue = (empty($nextValue) && $nextValue !== '0');
  862. if (!$isBoolean && !$emptyNextValue && !$this->_optionExists($nextValue)) {
  863. array_shift($this->_tokens);
  864. $value = $nextValue;
  865. } elseif ($isBoolean) {
  866. $value = true;
  867. } else {
  868. $value = $option->defaultValue();
  869. }
  870. if ($option->validChoice($value)) {
  871. if ($option->acceptsMultiple()) {
  872. $params[$name][] = $value;
  873. } else {
  874. $params[$name] = $value;
  875. }
  876. return $params;
  877. }
  878. return [];
  879. }
  880. /**
  881. * Check to see if $name has an option (short/long) defined for it.
  882. *
  883. * @param string $name The name of the option.
  884. * @return bool
  885. */
  886. protected function _optionExists($name)
  887. {
  888. if (substr($name, 0, 2) === '--') {
  889. return isset($this->_options[substr($name, 2)]);
  890. }
  891. if ($name{0} === '-' && $name{1} !== '-') {
  892. return isset($this->_shortOptions[$name{1}]);
  893. }
  894. return false;
  895. }
  896. /**
  897. * Parse an argument, and ensure that the argument doesn't exceed the number of arguments
  898. * and that the argument is a valid choice.
  899. *
  900. * @param string $argument The argument to append
  901. * @param array $args The array of parsed args to append to.
  902. * @return array Args
  903. * @throws \Cake\Console\Exception\ConsoleException
  904. */
  905. protected function _parseArg($argument, $args)
  906. {
  907. if (empty($this->_args)) {
  908. $args[] = $argument;
  909. return $args;
  910. }
  911. $next = count($args);
  912. if (!isset($this->_args[$next])) {
  913. throw new ConsoleException('Too many arguments.');
  914. }
  915. if ($this->_args[$next]->validChoice($argument)) {
  916. $args[] = $argument;
  917. return $args;
  918. }
  919. }
  920. /**
  921. * Find the next token in the argv set.
  922. *
  923. * @return string next token or ''
  924. */
  925. protected function _nextToken()
  926. {
  927. return isset($this->_tokens[0]) ? $this->_tokens[0] : '';
  928. }
  929. }