ConsoleOptionParser.php 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  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. * Subcommand sorting option
  116. *
  117. * @var bool
  118. */
  119. protected $_subcommandSort = true;
  120. /**
  121. * Command name.
  122. *
  123. * @var string
  124. */
  125. protected $_command = '';
  126. /**
  127. * Array of args (argv).
  128. *
  129. * @var array
  130. */
  131. protected $_tokens = [];
  132. /**
  133. * Root alias used in help output
  134. *
  135. * @see \Cake\Console\HelpFormatter::setAlias()
  136. * @var string
  137. */
  138. protected $rootName = 'cake';
  139. /**
  140. * Construct an OptionParser so you can define its behavior
  141. *
  142. * @param string|null $command The command name this parser is for. The command name is used for generating help.
  143. * @param bool $defaultOptions Whether you want the verbose and quiet options set. Setting
  144. * this to false will prevent the addition of `--verbose` & `--quiet` options.
  145. */
  146. public function __construct($command = null, $defaultOptions = true)
  147. {
  148. $this->setCommand($command);
  149. $this->addOption('help', [
  150. 'short' => 'h',
  151. 'help' => 'Display this help.',
  152. 'boolean' => true
  153. ]);
  154. if ($defaultOptions) {
  155. $this->addOption('verbose', [
  156. 'short' => 'v',
  157. 'help' => 'Enable verbose output.',
  158. 'boolean' => true
  159. ])->addOption('quiet', [
  160. 'short' => 'q',
  161. 'help' => 'Enable quiet output.',
  162. 'boolean' => true
  163. ]);
  164. }
  165. }
  166. /**
  167. * Static factory method for creating new OptionParsers so you can chain methods off of them.
  168. *
  169. * @param string|null $command The command name this parser is for. The command name is used for generating help.
  170. * @param bool $defaultOptions Whether you want the verbose and quiet options set.
  171. * @return static
  172. */
  173. public static function create($command, $defaultOptions = true)
  174. {
  175. return new static($command, $defaultOptions);
  176. }
  177. /**
  178. * Build a parser from an array. Uses an array like
  179. *
  180. * ```
  181. * $spec = [
  182. * 'description' => 'text',
  183. * 'epilog' => 'text',
  184. * 'arguments' => [
  185. * // list of arguments compatible with addArguments.
  186. * ],
  187. * 'options' => [
  188. * // list of options compatible with addOptions
  189. * ],
  190. * 'subcommands' => [
  191. * // list of subcommands to add.
  192. * ]
  193. * ];
  194. * ```
  195. *
  196. * @param array $spec The spec to build the OptionParser with.
  197. * @param bool $defaultOptions Whether you want the verbose and quiet options set.
  198. * @return static
  199. */
  200. public static function buildFromArray($spec, $defaultOptions = true)
  201. {
  202. $parser = new static($spec['command'], $defaultOptions);
  203. if (!empty($spec['arguments'])) {
  204. $parser->addArguments($spec['arguments']);
  205. }
  206. if (!empty($spec['options'])) {
  207. $parser->addOptions($spec['options']);
  208. }
  209. if (!empty($spec['subcommands'])) {
  210. $parser->addSubcommands($spec['subcommands']);
  211. }
  212. if (!empty($spec['description'])) {
  213. $parser->setDescription($spec['description']);
  214. }
  215. if (!empty($spec['epilog'])) {
  216. $parser->setEpilog($spec['epilog']);
  217. }
  218. return $parser;
  219. }
  220. /**
  221. * Returns an array representation of this parser.
  222. *
  223. * @return array
  224. */
  225. public function toArray()
  226. {
  227. $result = [
  228. 'command' => $this->_command,
  229. 'arguments' => $this->_args,
  230. 'options' => $this->_options,
  231. 'subcommands' => $this->_subcommands,
  232. 'description' => $this->_description,
  233. 'epilog' => $this->_epilog
  234. ];
  235. return $result;
  236. }
  237. /**
  238. * Get or set the command name for shell/task.
  239. *
  240. * @param array|\Cake\Console\ConsoleOptionParser $spec ConsoleOptionParser or spec to merge with.
  241. * @return $this
  242. */
  243. public function merge($spec)
  244. {
  245. if ($spec instanceof ConsoleOptionParser) {
  246. $spec = $spec->toArray();
  247. }
  248. if (!empty($spec['arguments'])) {
  249. $this->addArguments($spec['arguments']);
  250. }
  251. if (!empty($spec['options'])) {
  252. $this->addOptions($spec['options']);
  253. }
  254. if (!empty($spec['subcommands'])) {
  255. $this->addSubcommands($spec['subcommands']);
  256. }
  257. if (!empty($spec['description'])) {
  258. $this->setDescription($spec['description']);
  259. }
  260. if (!empty($spec['epilog'])) {
  261. $this->setEpilog($spec['epilog']);
  262. }
  263. return $this;
  264. }
  265. /**
  266. * Sets the command name for shell/task.
  267. *
  268. * @param string $text The text to set.
  269. * @return $this
  270. */
  271. public function setCommand($text)
  272. {
  273. $this->_command = Inflector::underscore($text);
  274. return $this;
  275. }
  276. /**
  277. * Gets the command name for shell/task.
  278. *
  279. * @return string The value of the command.
  280. */
  281. public function getCommand()
  282. {
  283. return $this->_command;
  284. }
  285. /**
  286. * Gets or sets the command name for shell/task.
  287. *
  288. * @deprecated 3.4.0 Use setCommand()/getCommand() instead.
  289. * @param string|null $text The text to set, or null if you want to read
  290. * @return string|$this If reading, the value of the command. If setting $this will be returned.
  291. */
  292. public function command($text = null)
  293. {
  294. deprecationWarning(
  295. 'ConsoleOptionParser::command() is deprecated. ' .
  296. 'Use ConsoleOptionParser::setCommand()/getCommand() instead.'
  297. );
  298. if ($text !== null) {
  299. return $this->setCommand($text);
  300. }
  301. return $this->getCommand();
  302. }
  303. /**
  304. * Sets the description text for shell/task.
  305. *
  306. * @param string|array $text The text to set. If an array the
  307. * text will be imploded with "\n".
  308. * @return $this
  309. */
  310. public function setDescription($text)
  311. {
  312. if (is_array($text)) {
  313. $text = implode("\n", $text);
  314. }
  315. $this->_description = $text;
  316. return $this;
  317. }
  318. /**
  319. * Gets the description text for shell/task.
  320. *
  321. * @return string The value of the description
  322. */
  323. public function getDescription()
  324. {
  325. return $this->_description;
  326. }
  327. /**
  328. * Get or set the description text for shell/task.
  329. *
  330. * @deprecated 3.4.0 Use setDescription()/getDescription() instead.
  331. * @param string|array|null $text The text to set, or null if you want to read. If an array the
  332. * text will be imploded with "\n".
  333. * @return string|$this If reading, the value of the description. If setting $this will be returned.
  334. */
  335. public function description($text = null)
  336. {
  337. deprecationWarning(
  338. 'ConsoleOptionParser::description() is deprecated. ' .
  339. 'Use ConsoleOptionParser::setDescription()/getDescription() instead.'
  340. );
  341. if ($text !== null) {
  342. return $this->setDescription($text);
  343. }
  344. return $this->getDescription();
  345. }
  346. /**
  347. * Sets an epilog to the parser. The epilog is added to the end of
  348. * the options and arguments listing when help is generated.
  349. *
  350. * @param string|array $text The text to set. If an array the text will
  351. * be imploded with "\n".
  352. * @return $this
  353. */
  354. public function setEpilog($text)
  355. {
  356. if (is_array($text)) {
  357. $text = implode("\n", $text);
  358. }
  359. $this->_epilog = $text;
  360. return $this;
  361. }
  362. /**
  363. * Gets the epilog.
  364. *
  365. * @return string The value of the epilog.
  366. */
  367. public function getEpilog()
  368. {
  369. return $this->_epilog;
  370. }
  371. /**
  372. * Gets or sets an epilog to the parser. The epilog is added to the end of
  373. * the options and arguments listing when help is generated.
  374. *
  375. * @deprecated 3.4.0 Use setEpilog()/getEpilog() instead.
  376. * @param string|array|null $text Text when setting or null when reading. If an array the text will
  377. * be imploded with "\n".
  378. * @return string|$this If reading, the value of the epilog. If setting $this will be returned.
  379. */
  380. public function epilog($text = null)
  381. {
  382. deprecationWarning(
  383. 'ConsoleOptionParser::epliog() is deprecated. ' .
  384. 'Use ConsoleOptionParser::setEpilog()/getEpilog() instead.'
  385. );
  386. if ($text !== null) {
  387. return $this->setEpilog($text);
  388. }
  389. return $this->getEpilog();
  390. }
  391. /**
  392. * Enables sorting of subcommands
  393. *
  394. * @param bool $value Whether or not to sort subcommands
  395. * @return $this
  396. */
  397. public function enableSubcommandSort($value = true)
  398. {
  399. $this->_subcommandSort = (bool)$value;
  400. return $this;
  401. }
  402. /**
  403. * Checks whether or not sorting is enabled for subcommands.
  404. *
  405. * @return bool
  406. */
  407. public function isSubcommandSortEnabled()
  408. {
  409. return $this->_subcommandSort;
  410. }
  411. /**
  412. * Add an option to the option parser. Options allow you to define optional or required
  413. * parameters for your console application. Options are defined by the parameters they use.
  414. *
  415. * ### Options
  416. *
  417. * - `short` - The single letter variant for this option, leave undefined for none.
  418. * - `help` - Help text for this option. Used when generating help for the option.
  419. * - `default` - The default value for this option. Defaults are added into the parsed params when the
  420. * attached option is not provided or has no value. Using default and boolean together will not work.
  421. * are added into the parsed parameters when the option is undefined. Defaults to null.
  422. * - `boolean` - The option uses no value, it's just a boolean switch. Defaults to false.
  423. * If an option is defined as boolean, it will always be added to the parsed params. If no present
  424. * it will be false, if present it will be true.
  425. * - `multiple` - The option can be provided multiple times. The parsed option
  426. * will be an array of values when this option is enabled.
  427. * - `choices` A list of valid choices for this option. If left empty all values are valid..
  428. * An exception will be raised when parse() encounters an invalid value.
  429. *
  430. * @param \Cake\Console\ConsoleInputOption|string $name The long name you want to the value to be parsed out as when options are parsed.
  431. * Will also accept an instance of ConsoleInputOption
  432. * @param array $options An array of parameters that define the behavior of the option
  433. * @return $this
  434. */
  435. public function addOption($name, array $options = [])
  436. {
  437. if ($name instanceof ConsoleInputOption) {
  438. $option = $name;
  439. $name = $option->name();
  440. } else {
  441. $defaults = [
  442. 'name' => $name,
  443. 'short' => null,
  444. 'help' => '',
  445. 'default' => null,
  446. 'boolean' => false,
  447. 'choices' => []
  448. ];
  449. $options += $defaults;
  450. $option = new ConsoleInputOption($options);
  451. }
  452. $this->_options[$name] = $option;
  453. asort($this->_options);
  454. if ($option->short() !== null) {
  455. $this->_shortOptions[$option->short()] = $name;
  456. asort($this->_shortOptions);
  457. }
  458. return $this;
  459. }
  460. /**
  461. * Remove an option from the option parser.
  462. *
  463. * @param string $name The option name to remove.
  464. * @return $this
  465. */
  466. public function removeOption($name)
  467. {
  468. unset($this->_options[$name]);
  469. return $this;
  470. }
  471. /**
  472. * Add a positional argument to the option parser.
  473. *
  474. * ### Params
  475. *
  476. * - `help` The help text to display for this argument.
  477. * - `required` Whether this parameter is required.
  478. * - `index` The index for the arg, if left undefined the argument will be put
  479. * onto the end of the arguments. If you define the same index twice the first
  480. * option will be overwritten.
  481. * - `choices` A list of valid choices for this argument. If left empty all values are valid..
  482. * An exception will be raised when parse() encounters an invalid value.
  483. *
  484. * @param \Cake\Console\ConsoleInputArgument|string $name The name of the argument.
  485. * Will also accept an instance of ConsoleInputArgument.
  486. * @param array $params Parameters for the argument, see above.
  487. * @return $this
  488. */
  489. public function addArgument($name, array $params = [])
  490. {
  491. if ($name instanceof ConsoleInputArgument) {
  492. $arg = $name;
  493. $index = count($this->_args);
  494. } else {
  495. $defaults = [
  496. 'name' => $name,
  497. 'help' => '',
  498. 'index' => count($this->_args),
  499. 'required' => false,
  500. 'choices' => []
  501. ];
  502. $options = $params + $defaults;
  503. $index = $options['index'];
  504. unset($options['index']);
  505. $arg = new ConsoleInputArgument($options);
  506. }
  507. foreach ($this->_args as $k => $a) {
  508. if ($a->isEqualTo($arg)) {
  509. return $this;
  510. }
  511. if (!empty($options['required']) && !$a->isRequired()) {
  512. throw new LogicException('A required argument cannot follow an optional one');
  513. }
  514. }
  515. $this->_args[$index] = $arg;
  516. ksort($this->_args);
  517. return $this;
  518. }
  519. /**
  520. * Add multiple arguments at once. Take an array of argument definitions.
  521. * The keys are used as the argument names, and the values as params for the argument.
  522. *
  523. * @param array $args Array of arguments to add.
  524. * @see \Cake\Console\ConsoleOptionParser::addArgument()
  525. * @return $this
  526. */
  527. public function addArguments(array $args)
  528. {
  529. foreach ($args as $name => $params) {
  530. if ($params instanceof ConsoleInputArgument) {
  531. $name = $params;
  532. $params = [];
  533. }
  534. $this->addArgument($name, $params);
  535. }
  536. return $this;
  537. }
  538. /**
  539. * Add multiple options at once. Takes an array of option definitions.
  540. * The keys are used as option names, and the values as params for the option.
  541. *
  542. * @param array $options Array of options to add.
  543. * @see \Cake\Console\ConsoleOptionParser::addOption()
  544. * @return $this
  545. */
  546. public function addOptions(array $options)
  547. {
  548. foreach ($options as $name => $params) {
  549. if ($params instanceof ConsoleInputOption) {
  550. $name = $params;
  551. $params = [];
  552. }
  553. $this->addOption($name, $params);
  554. }
  555. return $this;
  556. }
  557. /**
  558. * Append a subcommand to the subcommand list.
  559. * Subcommands are usually methods on your Shell, but can also be used to document Tasks.
  560. *
  561. * ### Options
  562. *
  563. * - `help` - Help text for the subcommand.
  564. * - `parser` - A ConsoleOptionParser for the subcommand. This allows you to create method
  565. * specific option parsers. When help is generated for a subcommand, if a parser is present
  566. * it will be used.
  567. *
  568. * @param \Cake\Console\ConsoleInputSubcommand|string $name Name of the subcommand. Will also accept an instance of ConsoleInputSubcommand
  569. * @param array $options Array of params, see above.
  570. * @return $this
  571. */
  572. public function addSubcommand($name, array $options = [])
  573. {
  574. if ($name instanceof ConsoleInputSubcommand) {
  575. $command = $name;
  576. $name = $command->name();
  577. } else {
  578. $name = Inflector::underscore($name);
  579. $defaults = [
  580. 'name' => $name,
  581. 'help' => '',
  582. 'parser' => null
  583. ];
  584. $options += $defaults;
  585. $command = new ConsoleInputSubcommand($options);
  586. }
  587. $this->_subcommands[$name] = $command;
  588. if ($this->_subcommandSort) {
  589. asort($this->_subcommands);
  590. }
  591. return $this;
  592. }
  593. /**
  594. * Remove a subcommand from the option parser.
  595. *
  596. * @param string $name The subcommand name to remove.
  597. * @return $this
  598. */
  599. public function removeSubcommand($name)
  600. {
  601. unset($this->_subcommands[$name]);
  602. return $this;
  603. }
  604. /**
  605. * Add multiple subcommands at once.
  606. *
  607. * @param array $commands Array of subcommands.
  608. * @return $this
  609. */
  610. public function addSubcommands(array $commands)
  611. {
  612. foreach ($commands as $name => $params) {
  613. if ($params instanceof ConsoleInputSubcommand) {
  614. $name = $params;
  615. $params = [];
  616. }
  617. $this->addSubcommand($name, $params);
  618. }
  619. return $this;
  620. }
  621. /**
  622. * Gets the arguments defined in the parser.
  623. *
  624. * @return \Cake\Console\ConsoleInputArgument[]
  625. */
  626. public function arguments()
  627. {
  628. return $this->_args;
  629. }
  630. /**
  631. * Get the list of argument names.
  632. *
  633. * @return string[]
  634. */
  635. public function argumentNames()
  636. {
  637. $out = [];
  638. foreach ($this->_args as $arg) {
  639. $out[] = $arg->name();
  640. }
  641. return $out;
  642. }
  643. /**
  644. * Get the defined options in the parser.
  645. *
  646. * @return \Cake\Console\ConsoleInputOption[]
  647. */
  648. public function options()
  649. {
  650. return $this->_options;
  651. }
  652. /**
  653. * Get the array of defined subcommands
  654. *
  655. * @return \Cake\Console\ConsoleInputSubcommand[]
  656. */
  657. public function subcommands()
  658. {
  659. return $this->_subcommands;
  660. }
  661. /**
  662. * Parse the argv array into a set of params and args. If $command is not null
  663. * and $command is equal to a subcommand that has a parser, that parser will be used
  664. * to parse the $argv
  665. *
  666. * @param array $argv Array of args (argv) to parse.
  667. * @return array [$params, $args]
  668. * @throws \Cake\Console\Exception\ConsoleException When an invalid parameter is encountered.
  669. */
  670. public function parse($argv)
  671. {
  672. $command = isset($argv[0]) ? Inflector::underscore($argv[0]) : null;
  673. if (isset($this->_subcommands[$command])) {
  674. array_shift($argv);
  675. }
  676. if (isset($this->_subcommands[$command]) && $this->_subcommands[$command]->parser()) {
  677. return $this->_subcommands[$command]->parser()->parse($argv);
  678. }
  679. $params = $args = [];
  680. $this->_tokens = $argv;
  681. while (($token = array_shift($this->_tokens)) !== null) {
  682. if (isset($this->_subcommands[$token])) {
  683. continue;
  684. }
  685. if (substr($token, 0, 2) === '--') {
  686. $params = $this->_parseLongOption($token, $params);
  687. } elseif (substr($token, 0, 1) === '-') {
  688. $params = $this->_parseShortOption($token, $params);
  689. } else {
  690. $args = $this->_parseArg($token, $args);
  691. }
  692. }
  693. foreach ($this->_args as $i => $arg) {
  694. if ($arg->isRequired() && !isset($args[$i]) && empty($params['help'])) {
  695. throw new ConsoleException(
  696. sprintf('Missing required arguments. %s is required.', $arg->name())
  697. );
  698. }
  699. }
  700. foreach ($this->_options as $option) {
  701. $name = $option->name();
  702. $isBoolean = $option->isBoolean();
  703. $default = $option->defaultValue();
  704. if ($default !== null && !isset($params[$name]) && !$isBoolean) {
  705. $params[$name] = $default;
  706. }
  707. if ($isBoolean && !isset($params[$name])) {
  708. $params[$name] = false;
  709. }
  710. }
  711. return [$params, $args];
  712. }
  713. /**
  714. * Gets formatted help for this parser object.
  715. *
  716. * Generates help text based on the description, options, arguments, subcommands and epilog
  717. * in the parser.
  718. *
  719. * @param string|null $subcommand If present and a valid subcommand that has a linked parser.
  720. * That subcommands help will be shown instead.
  721. * @param string $format Define the output format, can be text or xml
  722. * @param int $width The width to format user content to. Defaults to 72
  723. * @return string Generated help.
  724. */
  725. public function help($subcommand = null, $format = 'text', $width = 72)
  726. {
  727. if ($subcommand === null) {
  728. $formatter = new HelpFormatter($this);
  729. $formatter->setAlias($this->rootName);
  730. if ($format === 'text') {
  731. return $formatter->text($width);
  732. }
  733. if ($format === 'xml') {
  734. return (string)$formatter->xml();
  735. }
  736. }
  737. if (isset($this->_subcommands[$subcommand])) {
  738. $command = $this->_subcommands[$subcommand];
  739. $subparser = $command->parser();
  740. // Generate a parser as the subcommand didn't define one.
  741. if (!($subparser instanceof self)) {
  742. // $subparser = clone $this;
  743. $subparser = new self($subcommand);
  744. $subparser
  745. ->setDescription($command->getRawHelp())
  746. ->addOptions($this->options())
  747. ->addArguments($this->arguments());
  748. }
  749. if (strlen($subparser->getDescription()) === 0) {
  750. $subparser->setDescription($command->getRawHelp());
  751. }
  752. $subparser->setCommand($this->getCommand() . ' ' . $subcommand);
  753. $subparser->setRootName($this->rootName);
  754. return $subparser->help(null, $format, $width);
  755. }
  756. return $this->getCommandError($subcommand);
  757. }
  758. /**
  759. * Set the alias used in the HelpFormatter
  760. *
  761. * @param string $alias The alias
  762. * @return void
  763. * @deprecated 3.5.0 Use setRootName() instead.
  764. */
  765. public function setHelpAlias($alias)
  766. {
  767. deprecationWarning(
  768. 'ConsoleOptionParser::setHelpAlias() is deprecated. ' .
  769. 'Use ConsoleOptionParser::setRootName() instead.'
  770. );
  771. $this->rootName = $alias;
  772. }
  773. /**
  774. * Set the root name used in the HelpFormatter
  775. *
  776. * @param string $name The root command name
  777. * @return $this
  778. */
  779. public function setRootName($name)
  780. {
  781. $this->rootName = (string)$name;
  782. return $this;
  783. }
  784. /**
  785. * Get the message output in the console stating that the command can not be found and tries to guess what the user
  786. * wanted to say. Output a list of available subcommands as well.
  787. *
  788. * @param string $command Unknown command name trying to be dispatched.
  789. * @return string The message to be displayed in the console.
  790. */
  791. protected function getCommandError($command)
  792. {
  793. $rootCommand = $this->getCommand();
  794. $subcommands = array_keys((array)$this->subcommands());
  795. $bestGuess = $this->findClosestItem($command, $subcommands);
  796. $out = [
  797. sprintf(
  798. 'Unable to find the `%s %s` subcommand. See `bin/%s %s --help`.',
  799. $rootCommand,
  800. $command,
  801. $this->rootName,
  802. $rootCommand
  803. ),
  804. ''
  805. ];
  806. if ($bestGuess !== null) {
  807. $out[] = sprintf('Did you mean : `%s %s` ?', $rootCommand, $bestGuess);
  808. $out[] = '';
  809. }
  810. $out[] = sprintf('Available subcommands for the `%s` command are : ', $rootCommand);
  811. $out[] = '';
  812. foreach ($subcommands as $subcommand) {
  813. $out[] = ' - ' . $subcommand;
  814. }
  815. return implode("\n", $out);
  816. }
  817. /**
  818. * Get the message output in the console stating that the option can not be found and tries to guess what the user
  819. * wanted to say. Output a list of available options as well.
  820. *
  821. * @param string $option Unknown option name trying to be used.
  822. * @return string The message to be displayed in the console.
  823. */
  824. protected function getOptionError($option)
  825. {
  826. $availableOptions = array_keys($this->_options);
  827. $bestGuess = $this->findClosestItem($option, $availableOptions);
  828. $out = [
  829. sprintf('Unknown option `%s`.', $option),
  830. ''
  831. ];
  832. if ($bestGuess !== null) {
  833. $out[] = sprintf('Did you mean `%s` ?', $bestGuess);
  834. $out[] = '';
  835. }
  836. $out[] = 'Available options are :';
  837. $out[] = '';
  838. foreach ($availableOptions as $availableOption) {
  839. $out[] = ' - ' . $availableOption;
  840. }
  841. return implode("\n", $out);
  842. }
  843. /**
  844. * Get the message output in the console stating that the short option can not be found. Output a list of available
  845. * short options and what option they refer to as well.
  846. *
  847. * @param string $option Unknown short option name trying to be used.
  848. * @return string The message to be displayed in the console.
  849. */
  850. protected function getShortOptionError($option)
  851. {
  852. $out = [sprintf('Unknown short option `%s`', $option)];
  853. $out[] = '';
  854. $out[] = 'Available short options are :';
  855. $out[] = '';
  856. foreach ($this->_shortOptions as $short => $long) {
  857. $out[] = sprintf(' - `%s` (short for `--%s`)', $short, $long);
  858. }
  859. return implode("\n", $out);
  860. }
  861. /**
  862. * Tries to guess the item name the user originally wanted using the some regex pattern and the levenshtein
  863. * algorithm.
  864. *
  865. * @param string $needle Unknown item (either a subcommand name or an option for instance) trying to be used.
  866. * @param array $haystack List of items available for the type $needle belongs to.
  867. * @return string|null The closest name to the item submitted by the user.
  868. */
  869. protected function findClosestItem($needle, $haystack)
  870. {
  871. $bestGuess = null;
  872. foreach ($haystack as $item) {
  873. if (preg_match('/^' . $needle . '/', $item)) {
  874. return $item;
  875. }
  876. }
  877. foreach ($haystack as $item) {
  878. if (preg_match('/' . $needle . '/', $item)) {
  879. return $item;
  880. }
  881. $score = levenshtein($needle, $item);
  882. if (!isset($bestScore) || $score < $bestScore) {
  883. $bestScore = $score;
  884. $bestGuess = $item;
  885. }
  886. }
  887. return $bestGuess;
  888. }
  889. /**
  890. * Parse the value for a long option out of $this->_tokens. Will handle
  891. * options with an `=` in them.
  892. *
  893. * @param string $option The option to parse.
  894. * @param array $params The params to append the parsed value into
  895. * @return array Params with $option added in.
  896. */
  897. protected function _parseLongOption($option, $params)
  898. {
  899. $name = substr($option, 2);
  900. if (strpos($name, '=') !== false) {
  901. list($name, $value) = explode('=', $name, 2);
  902. array_unshift($this->_tokens, $value);
  903. }
  904. return $this->_parseOption($name, $params);
  905. }
  906. /**
  907. * Parse the value for a short option out of $this->_tokens
  908. * If the $option is a combination of multiple shortcuts like -otf
  909. * they will be shifted onto the token stack and parsed individually.
  910. *
  911. * @param string $option The option to parse.
  912. * @param array $params The params to append the parsed value into
  913. * @return array Params with $option added in.
  914. * @throws \Cake\Console\Exception\ConsoleException When unknown short options are encountered.
  915. */
  916. protected function _parseShortOption($option, $params)
  917. {
  918. $key = substr($option, 1);
  919. if (strlen($key) > 1) {
  920. $flags = str_split($key);
  921. $key = $flags[0];
  922. for ($i = 1, $len = count($flags); $i < $len; $i++) {
  923. array_unshift($this->_tokens, '-' . $flags[$i]);
  924. }
  925. }
  926. if (!isset($this->_shortOptions[$key])) {
  927. throw new ConsoleException($this->getShortOptionError($key));
  928. }
  929. $name = $this->_shortOptions[$key];
  930. return $this->_parseOption($name, $params);
  931. }
  932. /**
  933. * Parse an option by its name index.
  934. *
  935. * @param string $name The name to parse.
  936. * @param array $params The params to append the parsed value into
  937. * @return array Params with $option added in.
  938. * @throws \Cake\Console\Exception\ConsoleException
  939. */
  940. protected function _parseOption($name, $params)
  941. {
  942. if (!isset($this->_options[$name])) {
  943. throw new ConsoleException($this->getOptionError($name));
  944. }
  945. $option = $this->_options[$name];
  946. $isBoolean = $option->isBoolean();
  947. $nextValue = $this->_nextToken();
  948. $emptyNextValue = (empty($nextValue) && $nextValue !== '0');
  949. if (!$isBoolean && !$emptyNextValue && !$this->_optionExists($nextValue)) {
  950. array_shift($this->_tokens);
  951. $value = $nextValue;
  952. } elseif ($isBoolean) {
  953. $value = true;
  954. } else {
  955. $value = $option->defaultValue();
  956. }
  957. if ($option->validChoice($value)) {
  958. if ($option->acceptsMultiple()) {
  959. $params[$name][] = $value;
  960. } else {
  961. $params[$name] = $value;
  962. }
  963. return $params;
  964. }
  965. return [];
  966. }
  967. /**
  968. * Check to see if $name has an option (short/long) defined for it.
  969. *
  970. * @param string $name The name of the option.
  971. * @return bool
  972. */
  973. protected function _optionExists($name)
  974. {
  975. if (substr($name, 0, 2) === '--') {
  976. return isset($this->_options[substr($name, 2)]);
  977. }
  978. if ($name{0} === '-' && $name{1} !== '-') {
  979. return isset($this->_shortOptions[$name{1}]);
  980. }
  981. return false;
  982. }
  983. /**
  984. * Parse an argument, and ensure that the argument doesn't exceed the number of arguments
  985. * and that the argument is a valid choice.
  986. *
  987. * @param string $argument The argument to append
  988. * @param array $args The array of parsed args to append to.
  989. * @return array Args
  990. * @throws \Cake\Console\Exception\ConsoleException
  991. */
  992. protected function _parseArg($argument, $args)
  993. {
  994. if (empty($this->_args)) {
  995. $args[] = $argument;
  996. return $args;
  997. }
  998. $next = count($args);
  999. if (!isset($this->_args[$next])) {
  1000. throw new ConsoleException('Too many arguments.');
  1001. }
  1002. if ($this->_args[$next]->validChoice($argument)) {
  1003. $args[] = $argument;
  1004. return $args;
  1005. }
  1006. }
  1007. /**
  1008. * Find the next token in the argv set.
  1009. *
  1010. * @return string next token or ''
  1011. */
  1012. protected function _nextToken()
  1013. {
  1014. return isset($this->_tokens[0]) ? $this->_tokens[0] : '';
  1015. }
  1016. }