ConsoleOptionParser.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://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. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 2.0.0
  13. * @license http://www.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 = null;
  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 = null;
  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. * Construct an OptionParser so you can define its behavior
  128. *
  129. * @param string|null $command The command name this parser is for. The command name is used for generating help.
  130. * @param bool $defaultOptions Whether you want the verbose and quiet options set. Setting
  131. * this to false will prevent the addition of `--verbose` & `--quiet` options.
  132. */
  133. public function __construct($command = null, $defaultOptions = true)
  134. {
  135. $this->setCommand($command);
  136. $this->addOption('help', [
  137. 'short' => 'h',
  138. 'help' => 'Display this help.',
  139. 'boolean' => true
  140. ]);
  141. if ($defaultOptions) {
  142. $this->addOption('verbose', [
  143. 'short' => 'v',
  144. 'help' => 'Enable verbose output.',
  145. 'boolean' => true
  146. ])->addOption('quiet', [
  147. 'short' => 'q',
  148. 'help' => 'Enable quiet output.',
  149. 'boolean' => true
  150. ]);
  151. }
  152. }
  153. /**
  154. * Static factory method for creating new OptionParsers so you can chain methods off of them.
  155. *
  156. * @param string|null $command The command name this parser is for. The command name is used for generating help.
  157. * @param bool $defaultOptions Whether you want the verbose and quiet options set.
  158. * @return self
  159. */
  160. public static function create($command, $defaultOptions = true)
  161. {
  162. return new ConsoleOptionParser($command, $defaultOptions);
  163. }
  164. /**
  165. * Build a parser from an array. Uses an array like
  166. *
  167. * ```
  168. * $spec = [
  169. * 'description' => 'text',
  170. * 'epilog' => 'text',
  171. * 'arguments' => [
  172. * // list of arguments compatible with addArguments.
  173. * ],
  174. * 'options' => [
  175. * // list of options compatible with addOptions
  176. * ],
  177. * 'subcommands' => [
  178. * // list of subcommands to add.
  179. * ]
  180. * ];
  181. * ```
  182. *
  183. * @param array $spec The spec to build the OptionParser with.
  184. * @param bool $defaultOptions Whether you want the verbose and quiet options set.
  185. * @return self
  186. */
  187. public static function buildFromArray($spec, $defaultOptions = true)
  188. {
  189. $parser = new ConsoleOptionParser($spec['command'], $defaultOptions);
  190. if (!empty($spec['arguments'])) {
  191. $parser->addArguments($spec['arguments']);
  192. }
  193. if (!empty($spec['options'])) {
  194. $parser->addOptions($spec['options']);
  195. }
  196. if (!empty($spec['subcommands'])) {
  197. $parser->addSubcommands($spec['subcommands']);
  198. }
  199. if (!empty($spec['description'])) {
  200. $parser->setDescription($spec['description']);
  201. }
  202. if (!empty($spec['epilog'])) {
  203. $parser->setEpilog($spec['epilog']);
  204. }
  205. return $parser;
  206. }
  207. /**
  208. * Returns an array representation of this parser.
  209. *
  210. * @return array
  211. */
  212. public function toArray()
  213. {
  214. $result = [
  215. 'command' => $this->_command,
  216. 'arguments' => $this->_args,
  217. 'options' => $this->_options,
  218. 'subcommands' => $this->_subcommands,
  219. 'description' => $this->_description,
  220. 'epilog' => $this->_epilog
  221. ];
  222. return $result;
  223. }
  224. /**
  225. * Get or set the command name for shell/task.
  226. *
  227. * @param array|\Cake\Console\ConsoleOptionParser $spec ConsoleOptionParser or spec to merge with.
  228. * @return self
  229. */
  230. public function merge($spec)
  231. {
  232. if ($spec instanceof ConsoleOptionParser) {
  233. $spec = $spec->toArray();
  234. }
  235. if (!empty($spec['arguments'])) {
  236. $this->addArguments($spec['arguments']);
  237. }
  238. if (!empty($spec['options'])) {
  239. $this->addOptions($spec['options']);
  240. }
  241. if (!empty($spec['subcommands'])) {
  242. $this->addSubcommands($spec['subcommands']);
  243. }
  244. if (!empty($spec['description'])) {
  245. $this->setDescription($spec['description']);
  246. }
  247. if (!empty($spec['epilog'])) {
  248. $this->setEpilog($spec['epilog']);
  249. }
  250. return $this;
  251. }
  252. /**
  253. * Sets the command name for shell/task.
  254. *
  255. * @param string $text The text to set.
  256. * @return self
  257. */
  258. public function setCommand($text)
  259. {
  260. $this->_command = Inflector::underscore($text);
  261. return $this;
  262. }
  263. /**
  264. * Gets the command name for shell/task.
  265. *
  266. * @return string The value of the command.
  267. */
  268. public function getCommand()
  269. {
  270. return $this->_command;
  271. }
  272. /**
  273. * Gets or sets the command name for shell/task.
  274. *
  275. * @deprecated 3.4.0 Use setCommand()/getCommand() instead.
  276. * @param string|null $text The text to set, or null if you want to read
  277. * @return string|self If reading, the value of the command. If setting $this will be returned.
  278. */
  279. public function command($text = null)
  280. {
  281. if ($text !== null) {
  282. return $this->setCommand($text);
  283. }
  284. return $this->getCommand();
  285. }
  286. /**
  287. * Sets the description text for shell/task.
  288. *
  289. * @param string|array $text The text to set. If an array the
  290. * text will be imploded with "\n".
  291. * @return self
  292. */
  293. public function setDescription($text)
  294. {
  295. if (is_array($text)) {
  296. $text = implode("\n", $text);
  297. }
  298. $this->_description = $text;
  299. return $this;
  300. }
  301. /**
  302. * Gets the description text for shell/task.
  303. *
  304. * @return string The value of the description
  305. */
  306. public function getDescription()
  307. {
  308. return $this->_description;
  309. }
  310. /**
  311. * Get or set the description text for shell/task.
  312. *
  313. * @deprecated 3.4.0 Use setDescription()/getDescription() instead.
  314. * @param string|array|null $text The text to set, or null if you want to read. If an array the
  315. * text will be imploded with "\n".
  316. * @return string|self If reading, the value of the description. If setting $this will be returned.
  317. */
  318. public function description($text = null)
  319. {
  320. if ($text !== null) {
  321. return $this->setDescription($text);
  322. }
  323. return $this->getDescription();
  324. }
  325. /**
  326. * Sets an epilog to the parser. The epilog is added to the end of
  327. * the options and arguments listing when help is generated.
  328. *
  329. * @param string|array $text The text to set. If an array the text will
  330. * be imploded with "\n".
  331. * @return self
  332. */
  333. public function setEpilog($text)
  334. {
  335. if (is_array($text)) {
  336. $text = implode("\n", $text);
  337. }
  338. $this->_epilog = $text;
  339. return $this;
  340. }
  341. /**
  342. * Gets the epilog.
  343. *
  344. * @return string The value of the epilog.
  345. */
  346. public function getEpilog()
  347. {
  348. return $this->_epilog;
  349. }
  350. /**
  351. * Gets or sets an epilog to the parser. The epilog is added to the end of
  352. * the options and arguments listing when help is generated.
  353. *
  354. * @deprecated 3.4.0 Use setEpilog()/getEpilog() instead.
  355. * @param string|array|null $text Text when setting or null when reading. If an array the text will
  356. * be imploded with "\n".
  357. * @return string|self If reading, the value of the epilog. If setting $this will be returned.
  358. */
  359. public function epilog($text = null)
  360. {
  361. if ($text !== null) {
  362. return $this->setEpilog($text);
  363. }
  364. return $this->getEpilog();
  365. }
  366. /**
  367. * Add an option to the option parser. Options allow you to define optional or required
  368. * parameters for your console application. Options are defined by the parameters they use.
  369. *
  370. * ### Options
  371. *
  372. * - `short` - The single letter variant for this option, leave undefined for none.
  373. * - `help` - Help text for this option. Used when generating help for the option.
  374. * - `default` - The default value for this option. Defaults are added into the parsed params when the
  375. * attached option is not provided or has no value. Using default and boolean together will not work.
  376. * are added into the parsed parameters when the option is undefined. Defaults to null.
  377. * - `boolean` - The option uses no value, it's just a boolean switch. Defaults to false.
  378. * If an option is defined as boolean, it will always be added to the parsed params. If no present
  379. * it will be false, if present it will be true.
  380. * - `choices` A list of valid choices for this option. If left empty all values are valid..
  381. * An exception will be raised when parse() encounters an invalid value.
  382. *
  383. * @param \Cake\Console\ConsoleInputOption|string $name The long name you want to the value to be parsed out as when options are parsed.
  384. * Will also accept an instance of ConsoleInputOption
  385. * @param array $options An array of parameters that define the behavior of the option
  386. * @return self
  387. */
  388. public function addOption($name, array $options = [])
  389. {
  390. if ($name instanceof ConsoleInputOption) {
  391. $option = $name;
  392. $name = $option->name();
  393. } else {
  394. $defaults = [
  395. 'name' => $name,
  396. 'short' => null,
  397. 'help' => '',
  398. 'default' => null,
  399. 'boolean' => false,
  400. 'choices' => []
  401. ];
  402. $options += $defaults;
  403. $option = new ConsoleInputOption($options);
  404. }
  405. $this->_options[$name] = $option;
  406. asort($this->_options);
  407. if ($option->short() !== null) {
  408. $this->_shortOptions[$option->short()] = $name;
  409. asort($this->_shortOptions);
  410. }
  411. return $this;
  412. }
  413. /**
  414. * Remove an option from the option parser.
  415. *
  416. * @param string $name The option name to remove.
  417. * @return self
  418. */
  419. public function removeOption($name)
  420. {
  421. unset($this->_options[$name]);
  422. return $this;
  423. }
  424. /**
  425. * Add a positional argument to the option parser.
  426. *
  427. * ### Params
  428. *
  429. * - `help` The help text to display for this argument.
  430. * - `required` Whether this parameter is required.
  431. * - `index` The index for the arg, if left undefined the argument will be put
  432. * onto the end of the arguments. If you define the same index twice the first
  433. * option will be overwritten.
  434. * - `choices` A list of valid choices for this argument. If left empty all values are valid..
  435. * An exception will be raised when parse() encounters an invalid value.
  436. *
  437. * @param \Cake\Console\ConsoleInputArgument|string $name The name of the argument.
  438. * Will also accept an instance of ConsoleInputArgument.
  439. * @param array $params Parameters for the argument, see above.
  440. * @return self
  441. */
  442. public function addArgument($name, array $params = [])
  443. {
  444. if ($name instanceof ConsoleInputArgument) {
  445. $arg = $name;
  446. $index = count($this->_args);
  447. } else {
  448. $defaults = [
  449. 'name' => $name,
  450. 'help' => '',
  451. 'index' => count($this->_args),
  452. 'required' => false,
  453. 'choices' => []
  454. ];
  455. $options = $params + $defaults;
  456. $index = $options['index'];
  457. unset($options['index']);
  458. $arg = new ConsoleInputArgument($options);
  459. }
  460. foreach ($this->_args as $k => $a) {
  461. if ($a->isEqualTo($arg)) {
  462. return $this;
  463. }
  464. if (!empty($options['required']) && !$a->isRequired()) {
  465. throw new LogicException('A required argument cannot follow an optional one');
  466. }
  467. }
  468. $this->_args[$index] = $arg;
  469. ksort($this->_args);
  470. return $this;
  471. }
  472. /**
  473. * Add multiple arguments at once. Take an array of argument definitions.
  474. * The keys are used as the argument names, and the values as params for the argument.
  475. *
  476. * @param array $args Array of arguments to add.
  477. * @see \Cake\Console\ConsoleOptionParser::addArgument()
  478. * @return self
  479. */
  480. public function addArguments(array $args)
  481. {
  482. foreach ($args as $name => $params) {
  483. if ($params instanceof ConsoleInputArgument) {
  484. $name = $params;
  485. $params = [];
  486. }
  487. $this->addArgument($name, $params);
  488. }
  489. return $this;
  490. }
  491. /**
  492. * Add multiple options at once. Takes an array of option definitions.
  493. * The keys are used as option names, and the values as params for the option.
  494. *
  495. * @param array $options Array of options to add.
  496. * @see \Cake\Console\ConsoleOptionParser::addOption()
  497. * @return self
  498. */
  499. public function addOptions(array $options)
  500. {
  501. foreach ($options as $name => $params) {
  502. if ($params instanceof ConsoleInputOption) {
  503. $name = $params;
  504. $params = [];
  505. }
  506. $this->addOption($name, $params);
  507. }
  508. return $this;
  509. }
  510. /**
  511. * Append a subcommand to the subcommand list.
  512. * Subcommands are usually methods on your Shell, but can also be used to document Tasks.
  513. *
  514. * ### Options
  515. *
  516. * - `help` - Help text for the subcommand.
  517. * - `parser` - A ConsoleOptionParser for the subcommand. This allows you to create method
  518. * specific option parsers. When help is generated for a subcommand, if a parser is present
  519. * it will be used.
  520. *
  521. * @param \Cake\Console\ConsoleInputSubcommand|string $name Name of the subcommand. Will also accept an instance of ConsoleInputSubcommand
  522. * @param array $options Array of params, see above.
  523. * @return self
  524. */
  525. public function addSubcommand($name, array $options = [])
  526. {
  527. if ($name instanceof ConsoleInputSubcommand) {
  528. $command = $name;
  529. $name = $command->name();
  530. } else {
  531. $defaults = [
  532. 'name' => $name,
  533. 'help' => '',
  534. 'parser' => null
  535. ];
  536. $options += $defaults;
  537. $options = $this->_mergeSubcommandHelpToParserDescription($options);
  538. $command = new ConsoleInputSubcommand($options);
  539. }
  540. $this->_subcommands[$name] = $command;
  541. asort($this->_subcommands);
  542. return $this;
  543. }
  544. /**
  545. * @param array $options Options
  546. * @return array
  547. */
  548. protected function _mergeSubcommandHelpToParserDescription($options)
  549. {
  550. if (!$options['help']) {
  551. return $options;
  552. }
  553. if ($options['parser'] instanceof self) {
  554. if ($options['parser']->getDescription() !== null) {
  555. return $options;
  556. }
  557. $options['parser']->setDescription($options['help']);
  558. return $options;
  559. }
  560. if (is_array($options['parser'])) {
  561. if (isset($options['parser']['description'])) {
  562. return $options;
  563. }
  564. }
  565. $options['parser'] = [
  566. 'description' => $options['help']
  567. ] + (array)$options['parser'];
  568. return $options;
  569. }
  570. /**
  571. * Remove a subcommand from the option parser.
  572. *
  573. * @param string $name The subcommand name to remove.
  574. * @return self
  575. */
  576. public function removeSubcommand($name)
  577. {
  578. unset($this->_subcommands[$name]);
  579. return $this;
  580. }
  581. /**
  582. * Add multiple subcommands at once.
  583. *
  584. * @param array $commands Array of subcommands.
  585. * @return self
  586. */
  587. public function addSubcommands(array $commands)
  588. {
  589. foreach ($commands as $name => $params) {
  590. if ($params instanceof ConsoleInputSubcommand) {
  591. $name = $params;
  592. $params = [];
  593. }
  594. $this->addSubcommand($name, $params);
  595. }
  596. return $this;
  597. }
  598. /**
  599. * Gets the arguments defined in the parser.
  600. *
  601. * @return array Array of argument descriptions
  602. */
  603. public function arguments()
  604. {
  605. return $this->_args;
  606. }
  607. /**
  608. * Get the defined options in the parser.
  609. *
  610. * @return array
  611. */
  612. public function options()
  613. {
  614. return $this->_options;
  615. }
  616. /**
  617. * Get the array of defined subcommands
  618. *
  619. * @return array
  620. */
  621. public function subcommands()
  622. {
  623. return $this->_subcommands;
  624. }
  625. /**
  626. * Parse the argv array into a set of params and args. If $command is not null
  627. * and $command is equal to a subcommand that has a parser, that parser will be used
  628. * to parse the $argv
  629. *
  630. * @param array $argv Array of args (argv) to parse.
  631. * @return array [$params, $args]
  632. * @throws \Cake\Console\Exception\ConsoleException When an invalid parameter is encountered.
  633. */
  634. public function parse($argv)
  635. {
  636. $command = isset($argv[0]) ? $argv[0] : null;
  637. if (isset($this->_subcommands[$command])) {
  638. array_shift($argv);
  639. }
  640. if (isset($this->_subcommands[$command]) && $this->_subcommands[$command]->parser()) {
  641. return $this->_subcommands[$command]->parser()->parse($argv);
  642. }
  643. $params = $args = [];
  644. $this->_tokens = $argv;
  645. while (($token = array_shift($this->_tokens)) !== null) {
  646. if (isset($this->_subcommands[$token])) {
  647. continue;
  648. }
  649. if (substr($token, 0, 2) === '--') {
  650. $params = $this->_parseLongOption($token, $params);
  651. } elseif (substr($token, 0, 1) === '-') {
  652. $params = $this->_parseShortOption($token, $params);
  653. } else {
  654. $args = $this->_parseArg($token, $args);
  655. }
  656. }
  657. foreach ($this->_args as $i => $arg) {
  658. if ($arg->isRequired() && !isset($args[$i]) && empty($params['help'])) {
  659. throw new ConsoleException(
  660. sprintf('Missing required arguments. %s is required.', $arg->name())
  661. );
  662. }
  663. }
  664. foreach ($this->_options as $option) {
  665. $name = $option->name();
  666. $isBoolean = $option->isBoolean();
  667. $default = $option->defaultValue();
  668. if ($default !== null && !isset($params[$name]) && !$isBoolean) {
  669. $params[$name] = $default;
  670. }
  671. if ($isBoolean && !isset($params[$name])) {
  672. $params[$name] = false;
  673. }
  674. }
  675. return [$params, $args];
  676. }
  677. /**
  678. * Gets formatted help for this parser object.
  679. * Generates help text based on the description, options, arguments, subcommands and epilog
  680. * in the parser.
  681. *
  682. * @param string|null $subcommand If present and a valid subcommand that has a linked parser.
  683. * That subcommands help will be shown instead.
  684. * @param string $format Define the output format, can be text or xml
  685. * @param int $width The width to format user content to. Defaults to 72
  686. * @return string Generated help.
  687. */
  688. public function help($subcommand = null, $format = 'text', $width = 72)
  689. {
  690. if (isset($this->_subcommands[$subcommand]) &&
  691. $this->_subcommands[$subcommand]->parser() instanceof self
  692. ) {
  693. $subparser = $this->_subcommands[$subcommand]->parser();
  694. $subparser->setCommand($this->getCommand() . ' ' . $subparser->getCommand());
  695. return $subparser->help(null, $format, $width);
  696. }
  697. $formatter = new HelpFormatter($this);
  698. if ($format === 'text') {
  699. return $formatter->text($width);
  700. }
  701. if ($format === 'xml') {
  702. return $formatter->xml();
  703. }
  704. }
  705. /**
  706. * Parse the value for a long option out of $this->_tokens. Will handle
  707. * options with an `=` in them.
  708. *
  709. * @param string $option The option to parse.
  710. * @param array $params The params to append the parsed value into
  711. * @return array Params with $option added in.
  712. */
  713. protected function _parseLongOption($option, $params)
  714. {
  715. $name = substr($option, 2);
  716. if (strpos($name, '=') !== false) {
  717. list($name, $value) = explode('=', $name, 2);
  718. array_unshift($this->_tokens, $value);
  719. }
  720. return $this->_parseOption($name, $params);
  721. }
  722. /**
  723. * Parse the value for a short option out of $this->_tokens
  724. * If the $option is a combination of multiple shortcuts like -otf
  725. * they will be shifted onto the token stack and parsed individually.
  726. *
  727. * @param string $option The option to parse.
  728. * @param array $params The params to append the parsed value into
  729. * @return array Params with $option added in.
  730. * @throws \Cake\Console\Exception\ConsoleException When unknown short options are encountered.
  731. */
  732. protected function _parseShortOption($option, $params)
  733. {
  734. $key = substr($option, 1);
  735. if (strlen($key) > 1) {
  736. $flags = str_split($key);
  737. $key = $flags[0];
  738. for ($i = 1, $len = count($flags); $i < $len; $i++) {
  739. array_unshift($this->_tokens, '-' . $flags[$i]);
  740. }
  741. }
  742. if (!isset($this->_shortOptions[$key])) {
  743. throw new ConsoleException(sprintf('Unknown short option `%s`', $key));
  744. }
  745. $name = $this->_shortOptions[$key];
  746. return $this->_parseOption($name, $params);
  747. }
  748. /**
  749. * Parse an option by its name index.
  750. *
  751. * @param string $name The name to parse.
  752. * @param array $params The params to append the parsed value into
  753. * @return array Params with $option added in.
  754. * @throws \Cake\Console\Exception\ConsoleException
  755. */
  756. protected function _parseOption($name, $params)
  757. {
  758. if (!isset($this->_options[$name])) {
  759. throw new ConsoleException(sprintf('Unknown option `%s`', $name));
  760. }
  761. $option = $this->_options[$name];
  762. $isBoolean = $option->isBoolean();
  763. $nextValue = $this->_nextToken();
  764. $emptyNextValue = (empty($nextValue) && $nextValue !== '0');
  765. if (!$isBoolean && !$emptyNextValue && !$this->_optionExists($nextValue)) {
  766. array_shift($this->_tokens);
  767. $value = $nextValue;
  768. } elseif ($isBoolean) {
  769. $value = true;
  770. } else {
  771. $value = $option->defaultValue();
  772. }
  773. if ($option->validChoice($value)) {
  774. $params[$name] = $value;
  775. return $params;
  776. }
  777. return [];
  778. }
  779. /**
  780. * Check to see if $name has an option (short/long) defined for it.
  781. *
  782. * @param string $name The name of the option.
  783. * @return bool
  784. */
  785. protected function _optionExists($name)
  786. {
  787. if (substr($name, 0, 2) === '--') {
  788. return isset($this->_options[substr($name, 2)]);
  789. }
  790. if ($name{0} === '-' && $name{1} !== '-') {
  791. return isset($this->_shortOptions[$name{1}]);
  792. }
  793. return false;
  794. }
  795. /**
  796. * Parse an argument, and ensure that the argument doesn't exceed the number of arguments
  797. * and that the argument is a valid choice.
  798. *
  799. * @param string $argument The argument to append
  800. * @param array $args The array of parsed args to append to.
  801. * @return array Args
  802. * @throws \Cake\Console\Exception\ConsoleException
  803. */
  804. protected function _parseArg($argument, $args)
  805. {
  806. if (empty($this->_args)) {
  807. $args[] = $argument;
  808. return $args;
  809. }
  810. $next = count($args);
  811. if (!isset($this->_args[$next])) {
  812. throw new ConsoleException('Too many arguments.');
  813. }
  814. if ($this->_args[$next]->validChoice($argument)) {
  815. $args[] = $argument;
  816. return $args;
  817. }
  818. }
  819. /**
  820. * Find the next token in the argv set.
  821. *
  822. * @return string next token or ''
  823. */
  824. protected function _nextToken()
  825. {
  826. return isset($this->_tokens[0]) ? $this->_tokens[0] : '';
  827. }
  828. }