ConsoleOptionParser.php 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  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. /**
  19. * Handles parsing the ARGV in the command line and provides support
  20. * for GetOpt compatible option definition. Provides a builder pattern implementation
  21. * for creating shell option parsers.
  22. *
  23. * ### Options
  24. *
  25. * Named arguments come in two forms, long and short. Long arguments are preceded
  26. * by two - and give a more verbose option name. i.e. `--version`. Short arguments are
  27. * preceded by one - and are only one character long. They usually match with a long option,
  28. * and provide a more terse alternative.
  29. *
  30. * ### Using Options
  31. *
  32. * Options can be defined with both long and short forms. By using `$parser->addOption()`
  33. * you can define new options. The name of the option is used as its long form, and you
  34. * can supply an additional short form, with the `short` option. Short options should
  35. * only be one letter long. Using more than one letter for a short option will raise an exception.
  36. *
  37. * Calling options can be done using syntax similar to most *nix command line tools. Long options
  38. * cane either include an `=` or leave it out.
  39. *
  40. * `cake myshell command --connection default --name=something`
  41. *
  42. * Short options can be defined singly or in groups.
  43. *
  44. * `cake myshell command -cn`
  45. *
  46. * Short options can be combined into groups as seen above. Each letter in a group
  47. * will be treated as a separate option. The previous example is equivalent to:
  48. *
  49. * `cake myshell command -c -n`
  50. *
  51. * Short options can also accept values:
  52. *
  53. * `cake myshell command -c default`
  54. *
  55. * ### Positional arguments
  56. *
  57. * If no positional arguments are defined, all of them will be parsed. If you define positional
  58. * arguments any arguments greater than those defined will cause exceptions. Additionally you can
  59. * declare arguments as optional, by setting the required param to false.
  60. *
  61. * ```
  62. * $parser->addArgument('model', ['required' => false]);
  63. * ```
  64. *
  65. * ### Providing Help text
  66. *
  67. * By providing help text for your positional arguments and named arguments, the ConsoleOptionParser
  68. * can generate a help display for you. You can view the help for shells by using the `--help` or `-h` switch.
  69. */
  70. class ConsoleOptionParser
  71. {
  72. /**
  73. * Description text - displays before options when help is generated
  74. *
  75. * @see \Cake\Console\ConsoleOptionParser::description()
  76. * @var string
  77. */
  78. protected $_description = null;
  79. /**
  80. * Epilog text - displays after options when help is generated
  81. *
  82. * @see \Cake\Console\ConsoleOptionParser::epilog()
  83. * @var string
  84. */
  85. protected $_epilog = null;
  86. /**
  87. * Option definitions.
  88. *
  89. * @see \Cake\Console\ConsoleOptionParser::addOption()
  90. * @var array
  91. */
  92. protected $_options = [];
  93. /**
  94. * Map of short -> long options, generated when using addOption()
  95. *
  96. * @var string
  97. */
  98. protected $_shortOptions = [];
  99. /**
  100. * Positional argument definitions.
  101. *
  102. * @see \Cake\Console\ConsoleOptionParser::addArgument()
  103. * @var array
  104. */
  105. protected $_args = [];
  106. /**
  107. * Subcommands for this Shell.
  108. *
  109. * @see \Cake\Console\ConsoleOptionParser::addSubcommand()
  110. * @var array
  111. */
  112. protected $_subcommands = [];
  113. /**
  114. * Command name.
  115. *
  116. * @var string
  117. */
  118. protected $_command = '';
  119. /**
  120. * Array of args (argv).
  121. *
  122. * @var array
  123. */
  124. protected $_tokens = [];
  125. /**
  126. * Construct an OptionParser so you can define its behavior
  127. *
  128. * @param string|null $command The command name this parser is for. The command name is used for generating help.
  129. * @param bool $defaultOptions Whether you want the verbose and quiet options set. Setting
  130. * this to false will prevent the addition of `--verbose` & `--quiet` options.
  131. */
  132. public function __construct($command = null, $defaultOptions = true)
  133. {
  134. $this->command($command);
  135. $this->addOption('help', [
  136. 'short' => 'h',
  137. 'help' => 'Display this help.',
  138. 'boolean' => true
  139. ]);
  140. if ($defaultOptions) {
  141. $this->addOption('verbose', [
  142. 'short' => 'v',
  143. 'help' => 'Enable verbose output.',
  144. 'boolean' => true
  145. ])->addOption('quiet', [
  146. 'short' => 'q',
  147. 'help' => 'Enable quiet output.',
  148. 'boolean' => true
  149. ]);
  150. }
  151. }
  152. /**
  153. * Static factory method for creating new OptionParsers so you can chain methods off of them.
  154. *
  155. * @param string|null $command The command name this parser is for. The command name is used for generating help.
  156. * @param bool $defaultOptions Whether you want the verbose and quiet options set.
  157. * @return $this
  158. */
  159. public static function create($command, $defaultOptions = true)
  160. {
  161. return new ConsoleOptionParser($command, $defaultOptions);
  162. }
  163. /**
  164. * Build a parser from an array. Uses an array like
  165. *
  166. * ```
  167. * $spec = [
  168. * 'description' => 'text',
  169. * 'epilog' => 'text',
  170. * 'arguments' => [
  171. * // list of arguments compatible with addArguments.
  172. * ],
  173. * 'options' => [
  174. * // list of options compatible with addOptions
  175. * ],
  176. * 'subcommands' => [
  177. * // list of subcommands to add.
  178. * ]
  179. * ];
  180. * ```
  181. *
  182. * @param array $spec The spec to build the OptionParser with.
  183. * @param bool $defaultOptions Whether you want the verbose and quiet options set.
  184. * @return $this
  185. */
  186. public static function buildFromArray($spec, $defaultOptions = true)
  187. {
  188. $parser = new ConsoleOptionParser($spec['command'], $defaultOptions);
  189. if (!empty($spec['arguments'])) {
  190. $parser->addArguments($spec['arguments']);
  191. }
  192. if (!empty($spec['options'])) {
  193. $parser->addOptions($spec['options']);
  194. }
  195. if (!empty($spec['subcommands'])) {
  196. $parser->addSubcommands($spec['subcommands']);
  197. }
  198. if (!empty($spec['description'])) {
  199. $parser->description($spec['description']);
  200. }
  201. if (!empty($spec['epilog'])) {
  202. $parser->epilog($spec['epilog']);
  203. }
  204. return $parser;
  205. }
  206. /**
  207. * Returns an array representation of this parser.
  208. *
  209. * @return array
  210. */
  211. public function toArray()
  212. {
  213. $result = [
  214. 'command' => $this->_command,
  215. 'arguments' => $this->_args,
  216. 'options' => $this->_options,
  217. 'subcommands' => $this->_subcommands,
  218. 'description' => $this->_description,
  219. 'epilog' => $this->_epilog
  220. ];
  221. return $result;
  222. }
  223. /**
  224. * Get or set the command name for shell/task.
  225. *
  226. * @param array|\Cake\Console\ConsoleOptionParser $spec ConsoleOptionParser or spec to merge with.
  227. * @return $this
  228. */
  229. public function merge($spec)
  230. {
  231. if ($spec instanceof ConsoleOptionParser) {
  232. $spec = $spec->toArray();
  233. }
  234. if (!empty($spec['arguments'])) {
  235. $this->addArguments($spec['arguments']);
  236. }
  237. if (!empty($spec['options'])) {
  238. $this->addOptions($spec['options']);
  239. }
  240. if (!empty($spec['subcommands'])) {
  241. $this->addSubcommands($spec['subcommands']);
  242. }
  243. if (!empty($spec['description'])) {
  244. $this->description($spec['description']);
  245. }
  246. if (!empty($spec['epilog'])) {
  247. $this->epilog($spec['epilog']);
  248. }
  249. return $this;
  250. }
  251. /**
  252. * Gets or sets the command name for shell/task.
  253. *
  254. * @param string|null $text The text to set, or null if you want to read
  255. * @return string|$this If reading, the value of the command. If setting $this will be returned.
  256. */
  257. public function command($text = null)
  258. {
  259. if ($text !== null) {
  260. $this->_command = Inflector::underscore($text);
  261. return $this;
  262. }
  263. return $this->_command;
  264. }
  265. /**
  266. * Get or set the description text for shell/task.
  267. *
  268. * @param string|array|null $text The text to set, or null if you want to read. If an array the
  269. * text will be imploded with "\n".
  270. * @return string|$this If reading, the value of the description. If setting $this will be returned.
  271. */
  272. public function description($text = null)
  273. {
  274. if ($text !== null) {
  275. if (is_array($text)) {
  276. $text = implode("\n", $text);
  277. }
  278. $this->_description = $text;
  279. return $this;
  280. }
  281. return $this->_description;
  282. }
  283. /**
  284. * Get or set an epilog to the parser. The epilog is added to the end of
  285. * the options and arguments listing when help is generated.
  286. *
  287. * @param string|array|null $text Text when setting or null when reading. If an array the text will
  288. * be imploded with "\n".
  289. * @return string|$this If reading, the value of the epilog. If setting $this will be returned.
  290. */
  291. public function epilog($text = null)
  292. {
  293. if ($text !== null) {
  294. if (is_array($text)) {
  295. $text = implode("\n", $text);
  296. }
  297. $this->_epilog = $text;
  298. return $this;
  299. }
  300. return $this->_epilog;
  301. }
  302. /**
  303. * Add an option to the option parser. Options allow you to define optional or required
  304. * parameters for your console application. Options are defined by the parameters they use.
  305. *
  306. * ### Options
  307. *
  308. * - `short` - The single letter variant for this option, leave undefined for none.
  309. * - `help` - Help text for this option. Used when generating help for the option.
  310. * - `default` - The default value for this option. Defaults are added into the parsed params when the
  311. * attached option is not provided or has no value. Using default and boolean together will not work.
  312. * are added into the parsed parameters when the option is undefined. Defaults to null.
  313. * - `boolean` - The option uses no value, it's just a boolean switch. Defaults to false.
  314. * If an option is defined as boolean, it will always be added to the parsed params. If no present
  315. * it will be false, if present it will be true.
  316. * - `multiple` - The option can be provided multiple times. The parsed option
  317. * will be an array of values when this option is enabled.
  318. * - `choices` A list of valid choices for this option. If left empty all values are valid..
  319. * An exception will be raised when parse() encounters an invalid value.
  320. *
  321. * @param \Cake\Console\ConsoleInputOption|string $name The long name you want to the value to be parsed out as when options are parsed.
  322. * Will also accept an instance of ConsoleInputOption
  323. * @param array $options An array of parameters that define the behavior of the option
  324. * @return $this
  325. */
  326. public function addOption($name, array $options = [])
  327. {
  328. if ($name instanceof ConsoleInputOption) {
  329. $option = $name;
  330. $name = $option->name();
  331. } else {
  332. $defaults = [
  333. 'name' => $name,
  334. 'short' => null,
  335. 'help' => '',
  336. 'default' => null,
  337. 'boolean' => false,
  338. 'choices' => []
  339. ];
  340. $options += $defaults;
  341. $option = new ConsoleInputOption($options);
  342. }
  343. $this->_options[$name] = $option;
  344. asort($this->_options);
  345. if ($option->short() !== null) {
  346. $this->_shortOptions[$option->short()] = $name;
  347. asort($this->_shortOptions);
  348. }
  349. return $this;
  350. }
  351. /**
  352. * Remove an option from the option parser.
  353. *
  354. * @param string $name The option name to remove.
  355. * @return $this
  356. */
  357. public function removeOption($name)
  358. {
  359. unset($this->_options[$name]);
  360. return $this;
  361. }
  362. /**
  363. * Add a positional argument to the option parser.
  364. *
  365. * ### Params
  366. *
  367. * - `help` The help text to display for this argument.
  368. * - `required` Whether this parameter is required.
  369. * - `index` The index for the arg, if left undefined the argument will be put
  370. * onto the end of the arguments. If you define the same index twice the first
  371. * option will be overwritten.
  372. * - `choices` A list of valid choices for this argument. If left empty all values are valid..
  373. * An exception will be raised when parse() encounters an invalid value.
  374. *
  375. * @param \Cake\Console\ConsoleInputArgument|string $name The name of the argument.
  376. * Will also accept an instance of ConsoleInputArgument.
  377. * @param array $params Parameters for the argument, see above.
  378. * @return $this
  379. */
  380. public function addArgument($name, array $params = [])
  381. {
  382. if ($name instanceof ConsoleInputArgument) {
  383. $arg = $name;
  384. $index = count($this->_args);
  385. } else {
  386. $defaults = [
  387. 'name' => $name,
  388. 'help' => '',
  389. 'index' => count($this->_args),
  390. 'required' => false,
  391. 'choices' => []
  392. ];
  393. $options = $params + $defaults;
  394. $index = $options['index'];
  395. unset($options['index']);
  396. $arg = new ConsoleInputArgument($options);
  397. }
  398. foreach ($this->_args as $k => $a) {
  399. if ($a->isEqualTo($arg)) {
  400. return $this;
  401. }
  402. }
  403. $this->_args[$index] = $arg;
  404. ksort($this->_args);
  405. return $this;
  406. }
  407. /**
  408. * Add multiple arguments at once. Take an array of argument definitions.
  409. * The keys are used as the argument names, and the values as params for the argument.
  410. *
  411. * @param array $args Array of arguments to add.
  412. * @see \Cake\Console\ConsoleOptionParser::addArgument()
  413. * @return $this
  414. */
  415. public function addArguments(array $args)
  416. {
  417. foreach ($args as $name => $params) {
  418. if ($params instanceof ConsoleInputArgument) {
  419. $name = $params;
  420. $params = [];
  421. }
  422. $this->addArgument($name, $params);
  423. }
  424. return $this;
  425. }
  426. /**
  427. * Add multiple options at once. Takes an array of option definitions.
  428. * The keys are used as option names, and the values as params for the option.
  429. *
  430. * @param array $options Array of options to add.
  431. * @see \Cake\Console\ConsoleOptionParser::addOption()
  432. * @return $this
  433. */
  434. public function addOptions(array $options)
  435. {
  436. foreach ($options as $name => $params) {
  437. if ($params instanceof ConsoleInputOption) {
  438. $name = $params;
  439. $params = [];
  440. }
  441. $this->addOption($name, $params);
  442. }
  443. return $this;
  444. }
  445. /**
  446. * Append a subcommand to the subcommand list.
  447. * Subcommands are usually methods on your Shell, but can also be used to document Tasks.
  448. *
  449. * ### Options
  450. *
  451. * - `help` - Help text for the subcommand.
  452. * - `parser` - A ConsoleOptionParser for the subcommand. This allows you to create method
  453. * specific option parsers. When help is generated for a subcommand, if a parser is present
  454. * it will be used.
  455. *
  456. * @param \Cake\Console\ConsoleInputSubcommand|string $name Name of the subcommand. Will also accept an instance of ConsoleInputSubcommand
  457. * @param array $options Array of params, see above.
  458. * @return $this
  459. */
  460. public function addSubcommand($name, array $options = [])
  461. {
  462. if ($name instanceof ConsoleInputSubcommand) {
  463. $command = $name;
  464. $name = $command->name();
  465. } else {
  466. $defaults = [
  467. 'name' => $name,
  468. 'help' => '',
  469. 'parser' => null
  470. ];
  471. $options += $defaults;
  472. $command = new ConsoleInputSubcommand($options);
  473. }
  474. $this->_subcommands[$name] = $command;
  475. asort($this->_subcommands);
  476. return $this;
  477. }
  478. /**
  479. * Remove a subcommand from the option parser.
  480. *
  481. * @param string $name The subcommand name to remove.
  482. * @return $this
  483. */
  484. public function removeSubcommand($name)
  485. {
  486. unset($this->_subcommands[$name]);
  487. return $this;
  488. }
  489. /**
  490. * Add multiple subcommands at once.
  491. *
  492. * @param array $commands Array of subcommands.
  493. * @return $this
  494. */
  495. public function addSubcommands(array $commands)
  496. {
  497. foreach ($commands as $name => $params) {
  498. if ($params instanceof ConsoleInputSubcommand) {
  499. $name = $params;
  500. $params = [];
  501. }
  502. $this->addSubcommand($name, $params);
  503. }
  504. return $this;
  505. }
  506. /**
  507. * Gets the arguments defined in the parser.
  508. *
  509. * @return array Array of argument descriptions
  510. */
  511. public function arguments()
  512. {
  513. return $this->_args;
  514. }
  515. /**
  516. * Get the defined options in the parser.
  517. *
  518. * @return array
  519. */
  520. public function options()
  521. {
  522. return $this->_options;
  523. }
  524. /**
  525. * Get the array of defined subcommands
  526. *
  527. * @return array
  528. */
  529. public function subcommands()
  530. {
  531. return $this->_subcommands;
  532. }
  533. /**
  534. * Parse the argv array into a set of params and args. If $command is not null
  535. * and $command is equal to a subcommand that has a parser, that parser will be used
  536. * to parse the $argv
  537. *
  538. * @param array $argv Array of args (argv) to parse.
  539. * @return array [$params, $args]
  540. * @throws \Cake\Console\Exception\ConsoleException When an invalid parameter is encountered.
  541. */
  542. public function parse($argv)
  543. {
  544. $command = isset($argv[0]) ? $argv[0] : null;
  545. if (isset($this->_subcommands[$command])) {
  546. array_shift($argv);
  547. }
  548. if (isset($this->_subcommands[$command]) && $this->_subcommands[$command]->parser()) {
  549. return $this->_subcommands[$command]->parser()->parse($argv);
  550. }
  551. $params = $args = [];
  552. $this->_tokens = $argv;
  553. while (($token = array_shift($this->_tokens)) !== null) {
  554. if (isset($this->_subcommands[$token])) {
  555. continue;
  556. }
  557. if (substr($token, 0, 2) === '--') {
  558. $params = $this->_parseLongOption($token, $params);
  559. } elseif (substr($token, 0, 1) === '-') {
  560. $params = $this->_parseShortOption($token, $params);
  561. } else {
  562. $args = $this->_parseArg($token, $args);
  563. }
  564. }
  565. foreach ($this->_args as $i => $arg) {
  566. if ($arg->isRequired() && !isset($args[$i]) && empty($params['help'])) {
  567. throw new ConsoleException(
  568. sprintf('Missing required arguments. %s is required.', $arg->name())
  569. );
  570. }
  571. }
  572. foreach ($this->_options as $option) {
  573. $name = $option->name();
  574. $isBoolean = $option->isBoolean();
  575. $default = $option->defaultValue();
  576. if ($default !== null && !isset($params[$name]) && !$isBoolean) {
  577. $params[$name] = $default;
  578. }
  579. if ($isBoolean && !isset($params[$name])) {
  580. $params[$name] = false;
  581. }
  582. }
  583. return [$params, $args];
  584. }
  585. /**
  586. * Gets formatted help for this parser object.
  587. * Generates help text based on the description, options, arguments, subcommands and epilog
  588. * in the parser.
  589. *
  590. * @param string|null $subcommand If present and a valid subcommand that has a linked parser.
  591. * That subcommands help will be shown instead.
  592. * @param string $format Define the output format, can be text or xml
  593. * @param int $width The width to format user content to. Defaults to 72
  594. * @return string Generated help.
  595. */
  596. public function help($subcommand = null, $format = 'text', $width = 72)
  597. {
  598. if (isset($this->_subcommands[$subcommand]) &&
  599. $this->_subcommands[$subcommand]->parser() instanceof self
  600. ) {
  601. $subparser = $this->_subcommands[$subcommand]->parser();
  602. $subparser->command($this->command() . ' ' . $subparser->command());
  603. return $subparser->help(null, $format, $width);
  604. }
  605. $formatter = new HelpFormatter($this);
  606. if ($format === 'text') {
  607. return $formatter->text($width);
  608. }
  609. if ($format === 'xml') {
  610. return $formatter->xml();
  611. }
  612. }
  613. /**
  614. * Parse the value for a long option out of $this->_tokens. Will handle
  615. * options with an `=` in them.
  616. *
  617. * @param string $option The option to parse.
  618. * @param array $params The params to append the parsed value into
  619. * @return array Params with $option added in.
  620. */
  621. protected function _parseLongOption($option, $params)
  622. {
  623. $name = substr($option, 2);
  624. if (strpos($name, '=') !== false) {
  625. list($name, $value) = explode('=', $name, 2);
  626. array_unshift($this->_tokens, $value);
  627. }
  628. return $this->_parseOption($name, $params);
  629. }
  630. /**
  631. * Parse the value for a short option out of $this->_tokens
  632. * If the $option is a combination of multiple shortcuts like -otf
  633. * they will be shifted onto the token stack and parsed individually.
  634. *
  635. * @param string $option The option to parse.
  636. * @param array $params The params to append the parsed value into
  637. * @return array Params with $option added in.
  638. * @throws \Cake\Console\Exception\ConsoleException When unknown short options are encountered.
  639. */
  640. protected function _parseShortOption($option, $params)
  641. {
  642. $key = substr($option, 1);
  643. if (strlen($key) > 1) {
  644. $flags = str_split($key);
  645. $key = $flags[0];
  646. for ($i = 1, $len = count($flags); $i < $len; $i++) {
  647. array_unshift($this->_tokens, '-' . $flags[$i]);
  648. }
  649. }
  650. if (!isset($this->_shortOptions[$key])) {
  651. throw new ConsoleException(sprintf('Unknown short option `%s`', $key));
  652. }
  653. $name = $this->_shortOptions[$key];
  654. return $this->_parseOption($name, $params);
  655. }
  656. /**
  657. * Parse an option by its name index.
  658. *
  659. * @param string $name The name to parse.
  660. * @param array $params The params to append the parsed value into
  661. * @return array Params with $option added in.
  662. * @throws \Cake\Console\Exception\ConsoleException
  663. */
  664. protected function _parseOption($name, $params)
  665. {
  666. if (!isset($this->_options[$name])) {
  667. throw new ConsoleException(sprintf('Unknown option `%s`', $name));
  668. }
  669. $option = $this->_options[$name];
  670. $isBoolean = $option->isBoolean();
  671. $nextValue = $this->_nextToken();
  672. $emptyNextValue = (empty($nextValue) && $nextValue !== '0');
  673. if (!$isBoolean && !$emptyNextValue && !$this->_optionExists($nextValue)) {
  674. array_shift($this->_tokens);
  675. $value = $nextValue;
  676. } elseif ($isBoolean) {
  677. $value = true;
  678. } else {
  679. $value = $option->defaultValue();
  680. }
  681. if ($option->validChoice($value)) {
  682. if ($option->acceptsMultiple($value)) {
  683. $params[$name][] = $value;
  684. } else {
  685. $params[$name] = $value;
  686. }
  687. return $params;
  688. }
  689. return [];
  690. }
  691. /**
  692. * Check to see if $name has an option (short/long) defined for it.
  693. *
  694. * @param string $name The name of the option.
  695. * @return bool
  696. */
  697. protected function _optionExists($name)
  698. {
  699. if (substr($name, 0, 2) === '--') {
  700. return isset($this->_options[substr($name, 2)]);
  701. }
  702. if ($name{0} === '-' && $name{1} !== '-') {
  703. return isset($this->_shortOptions[$name{1}]);
  704. }
  705. return false;
  706. }
  707. /**
  708. * Parse an argument, and ensure that the argument doesn't exceed the number of arguments
  709. * and that the argument is a valid choice.
  710. *
  711. * @param string $argument The argument to append
  712. * @param array $args The array of parsed args to append to.
  713. * @return array Args
  714. * @throws \Cake\Console\Exception\ConsoleException
  715. */
  716. protected function _parseArg($argument, $args)
  717. {
  718. if (empty($this->_args)) {
  719. $args[] = $argument;
  720. return $args;
  721. }
  722. $next = count($args);
  723. if (!isset($this->_args[$next])) {
  724. throw new ConsoleException('Too many arguments.');
  725. }
  726. if ($this->_args[$next]->validChoice($argument)) {
  727. $args[] = $argument;
  728. return $args;
  729. }
  730. }
  731. /**
  732. * Find the next token in the argv set.
  733. *
  734. * @return string next token or ''
  735. */
  736. protected function _nextToken()
  737. {
  738. return isset($this->_tokens[0]) ? $this->_tokens[0] : '';
  739. }
  740. }