ConsoleOptionParser.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777
  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. */
  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 array
  92. */
  93. protected $_options = [];
  94. /**
  95. * Map of short -> long options, generated when using addOption()
  96. *
  97. * @var string
  98. */
  99. protected $_shortOptions = [];
  100. /**
  101. * Positional argument definitions.
  102. *
  103. * @see \Cake\Console\ConsoleOptionParser::addArgument()
  104. * @var array
  105. */
  106. protected $_args = [];
  107. /**
  108. * Subcommands for this Shell.
  109. *
  110. * @see \Cake\Console\ConsoleOptionParser::addSubcommand()
  111. * @var array
  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->command($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 $this
  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 $this
  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->description($spec['description']);
  201. }
  202. if (!empty($spec['epilog'])) {
  203. $parser->epilog($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 $this
  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->description($spec['description']);
  246. }
  247. if (!empty($spec['epilog'])) {
  248. $this->epilog($spec['epilog']);
  249. }
  250. return $this;
  251. }
  252. /**
  253. * Gets or sets the command name for shell/task.
  254. *
  255. * @param string|null $text The text to set, or null if you want to read
  256. * @return string|$this If reading, the value of the command. If setting $this will be returned.
  257. */
  258. public function command($text = null)
  259. {
  260. if ($text !== null) {
  261. $this->_command = Inflector::underscore($text);
  262. return $this;
  263. }
  264. return $this->_command;
  265. }
  266. /**
  267. * Get or set the description text for shell/task.
  268. *
  269. * @param string|array|null $text The text to set, or null if you want to read. If an array the
  270. * text will be imploded with "\n".
  271. * @return string|$this If reading, the value of the description. If setting $this will be returned.
  272. */
  273. public function description($text = null)
  274. {
  275. if ($text !== null) {
  276. if (is_array($text)) {
  277. $text = implode("\n", $text);
  278. }
  279. $this->_description = $text;
  280. return $this;
  281. }
  282. return $this->_description;
  283. }
  284. /**
  285. * Get or set an epilog to the parser. The epilog is added to the end of
  286. * the options and arguments listing when help is generated.
  287. *
  288. * @param string|array|null $text Text when setting or null when reading. If an array the text will
  289. * be imploded with "\n".
  290. * @return string|$this If reading, the value of the epilog. If setting $this will be returned.
  291. */
  292. public function epilog($text = null)
  293. {
  294. if ($text !== null) {
  295. if (is_array($text)) {
  296. $text = implode("\n", $text);
  297. }
  298. $this->_epilog = $text;
  299. return $this;
  300. }
  301. return $this->_epilog;
  302. }
  303. /**
  304. * Add an option to the option parser. Options allow you to define optional or required
  305. * parameters for your console application. Options are defined by the parameters they use.
  306. *
  307. * ### Options
  308. *
  309. * - `short` - The single letter variant for this option, leave undefined for none.
  310. * - `help` - Help text for this option. Used when generating help for the option.
  311. * - `default` - The default value for this option. Defaults are added into the parsed params when the
  312. * attached option is not provided or has no value. Using default and boolean together will not work.
  313. * are added into the parsed parameters when the option is undefined. Defaults to null.
  314. * - `boolean` - The option uses no value, it's just a boolean switch. Defaults to false.
  315. * If an option is defined as boolean, it will always be added to the parsed params. If no present
  316. * it will be false, if present it will be true.
  317. * - `choices` A list of valid choices for this option. If left empty all values are valid..
  318. * An exception will be raised when parse() encounters an invalid value.
  319. *
  320. * @param \Cake\Console\ConsoleInputOption|string $name The long name you want to the value to be parsed out as when options are parsed.
  321. * Will also accept an instance of ConsoleInputOption
  322. * @param array $options An array of parameters that define the behavior of the option
  323. * @return $this
  324. */
  325. public function addOption($name, array $options = [])
  326. {
  327. if ($name instanceof ConsoleInputOption) {
  328. $option = $name;
  329. $name = $option->name();
  330. } else {
  331. $defaults = [
  332. 'name' => $name,
  333. 'short' => null,
  334. 'help' => '',
  335. 'default' => null,
  336. 'boolean' => false,
  337. 'choices' => []
  338. ];
  339. $options += $defaults;
  340. $option = new ConsoleInputOption($options);
  341. }
  342. $this->_options[$name] = $option;
  343. asort($this->_options);
  344. if ($option->short() !== null) {
  345. $this->_shortOptions[$option->short()] = $name;
  346. asort($this->_shortOptions);
  347. }
  348. return $this;
  349. }
  350. /**
  351. * Remove an option from the option parser.
  352. *
  353. * @param string $name The option name to remove.
  354. * @return $this
  355. */
  356. public function removeOption($name)
  357. {
  358. unset($this->_options[$name]);
  359. return $this;
  360. }
  361. /**
  362. * Add a positional argument to the option parser.
  363. *
  364. * ### Params
  365. *
  366. * - `help` The help text to display for this argument.
  367. * - `required` Whether this parameter is required.
  368. * - `index` The index for the arg, if left undefined the argument will be put
  369. * onto the end of the arguments. If you define the same index twice the first
  370. * option will be overwritten.
  371. * - `choices` A list of valid choices for this argument. If left empty all values are valid..
  372. * An exception will be raised when parse() encounters an invalid value.
  373. *
  374. * @param \Cake\Console\ConsoleInputArgument|string $name The name of the argument.
  375. * Will also accept an instance of ConsoleInputArgument.
  376. * @param array $params Parameters for the argument, see above.
  377. * @return $this
  378. */
  379. public function addArgument($name, array $params = [])
  380. {
  381. if ($name instanceof ConsoleInputArgument) {
  382. $arg = $name;
  383. $index = count($this->_args);
  384. } else {
  385. $defaults = [
  386. 'name' => $name,
  387. 'help' => '',
  388. 'index' => count($this->_args),
  389. 'required' => false,
  390. 'choices' => []
  391. ];
  392. $options = $params + $defaults;
  393. $index = $options['index'];
  394. unset($options['index']);
  395. $arg = new ConsoleInputArgument($options);
  396. }
  397. foreach ($this->_args as $k => $a) {
  398. if ($a->isEqualTo($arg)) {
  399. return $this;
  400. }
  401. }
  402. $this->_args[$index] = $arg;
  403. ksort($this->_args);
  404. return $this;
  405. }
  406. /**
  407. * Add multiple arguments at once. Take an array of argument definitions.
  408. * The keys are used as the argument names, and the values as params for the argument.
  409. *
  410. * @param array $args Array of arguments to add.
  411. * @see \Cake\Console\ConsoleOptionParser::addArgument()
  412. * @return $this
  413. */
  414. public function addArguments(array $args)
  415. {
  416. foreach ($args as $name => $params) {
  417. if ($params instanceof ConsoleInputArgument) {
  418. $name = $params;
  419. $params = [];
  420. }
  421. $this->addArgument($name, $params);
  422. }
  423. return $this;
  424. }
  425. /**
  426. * Add multiple options at once. Takes an array of option definitions.
  427. * The keys are used as option names, and the values as params for the option.
  428. *
  429. * @param array $options Array of options to add.
  430. * @see \Cake\Console\ConsoleOptionParser::addOption()
  431. * @return $this
  432. */
  433. public function addOptions(array $options)
  434. {
  435. foreach ($options as $name => $params) {
  436. if ($params instanceof ConsoleInputOption) {
  437. $name = $params;
  438. $params = [];
  439. }
  440. $this->addOption($name, $params);
  441. }
  442. return $this;
  443. }
  444. /**
  445. * Append a subcommand to the subcommand list.
  446. * Subcommands are usually methods on your Shell, but can also be used to document Tasks.
  447. *
  448. * ### Options
  449. *
  450. * - `help` - Help text for the subcommand.
  451. * - `parser` - A ConsoleOptionParser for the subcommand. This allows you to create method
  452. * specific option parsers. When help is generated for a subcommand, if a parser is present
  453. * it will be used.
  454. *
  455. * @param \Cake\Console\ConsoleInputSubcommand|string $name Name of the subcommand. Will also accept an instance of ConsoleInputSubcommand
  456. * @param array $options Array of params, see above.
  457. * @return $this
  458. */
  459. public function addSubcommand($name, array $options = [])
  460. {
  461. if ($name instanceof ConsoleInputSubcommand) {
  462. $command = $name;
  463. $name = $command->name();
  464. } else {
  465. $defaults = [
  466. 'name' => $name,
  467. 'help' => '',
  468. 'parser' => null
  469. ];
  470. $options += $defaults;
  471. $command = new ConsoleInputSubcommand($options);
  472. }
  473. $this->_subcommands[$name] = $command;
  474. asort($this->_subcommands);
  475. return $this;
  476. }
  477. /**
  478. * Remove a subcommand from the option parser.
  479. *
  480. * @param string $name The subcommand name to remove.
  481. * @return $this
  482. */
  483. public function removeSubcommand($name)
  484. {
  485. unset($this->_subcommands[$name]);
  486. return $this;
  487. }
  488. /**
  489. * Add multiple subcommands at once.
  490. *
  491. * @param array $commands Array of subcommands.
  492. * @return $this
  493. */
  494. public function addSubcommands(array $commands)
  495. {
  496. foreach ($commands as $name => $params) {
  497. if ($params instanceof ConsoleInputSubcommand) {
  498. $name = $params;
  499. $params = [];
  500. }
  501. $this->addSubcommand($name, $params);
  502. }
  503. return $this;
  504. }
  505. /**
  506. * Gets the arguments defined in the parser.
  507. *
  508. * @return array Array of argument descriptions
  509. */
  510. public function arguments()
  511. {
  512. return $this->_args;
  513. }
  514. /**
  515. * Get the defined options in the parser.
  516. *
  517. * @return array
  518. */
  519. public function options()
  520. {
  521. return $this->_options;
  522. }
  523. /**
  524. * Get the array of defined subcommands
  525. *
  526. * @return array
  527. */
  528. public function subcommands()
  529. {
  530. return $this->_subcommands;
  531. }
  532. /**
  533. * Parse the argv array into a set of params and args. If $command is not null
  534. * and $command is equal to a subcommand that has a parser, that parser will be used
  535. * to parse the $argv
  536. *
  537. * @param array $argv Array of args (argv) to parse.
  538. * @return array [$params, $args]
  539. * @throws \Cake\Console\Exception\ConsoleException When an invalid parameter is encountered.
  540. */
  541. public function parse($argv)
  542. {
  543. $command = isset($argv[0]) ? $argv[0] : null;
  544. if (isset($this->_subcommands[$command])) {
  545. array_shift($argv);
  546. }
  547. if (isset($this->_subcommands[$command]) && $this->_subcommands[$command]->parser()) {
  548. return $this->_subcommands[$command]->parser()->parse($argv);
  549. }
  550. $params = $args = [];
  551. $this->_tokens = $argv;
  552. while (($token = array_shift($this->_tokens)) !== null) {
  553. if (isset($this->_subcommands[$token])) {
  554. continue;
  555. }
  556. if (substr($token, 0, 2) === '--') {
  557. $params = $this->_parseLongOption($token, $params);
  558. } elseif (substr($token, 0, 1) === '-') {
  559. $params = $this->_parseShortOption($token, $params);
  560. } else {
  561. $args = $this->_parseArg($token, $args);
  562. }
  563. }
  564. foreach ($this->_args as $i => $arg) {
  565. if ($arg->isRequired() && !isset($args[$i]) && empty($params['help'])) {
  566. throw new ConsoleException(
  567. sprintf('Missing required arguments. %s is required.', $arg->name())
  568. );
  569. }
  570. }
  571. foreach ($this->_options as $option) {
  572. $name = $option->name();
  573. $isBoolean = $option->isBoolean();
  574. $default = $option->defaultValue();
  575. if ($default !== null && !isset($params[$name]) && !$isBoolean) {
  576. $params[$name] = $default;
  577. }
  578. if ($isBoolean && !isset($params[$name])) {
  579. $params[$name] = false;
  580. }
  581. }
  582. return [$params, $args];
  583. }
  584. /**
  585. * Gets formatted help for this parser object.
  586. * Generates help text based on the description, options, arguments, subcommands and epilog
  587. * in the parser.
  588. *
  589. * @param string|null $subcommand If present and a valid subcommand that has a linked parser.
  590. * That subcommands help will be shown instead.
  591. * @param string $format Define the output format, can be text or xml
  592. * @param int $width The width to format user content to. Defaults to 72
  593. * @return string Generated help.
  594. */
  595. public function help($subcommand = null, $format = 'text', $width = 72)
  596. {
  597. if (isset($this->_subcommands[$subcommand]) &&
  598. $this->_subcommands[$subcommand]->parser() instanceof self
  599. ) {
  600. $subparser = $this->_subcommands[$subcommand]->parser();
  601. $subparser->command($this->command() . ' ' . $subparser->command());
  602. return $subparser->help(null, $format, $width);
  603. }
  604. $formatter = new HelpFormatter($this);
  605. if ($format === 'text') {
  606. return $formatter->text($width);
  607. }
  608. if ($format === 'xml') {
  609. return $formatter->xml();
  610. }
  611. }
  612. /**
  613. * Parse the value for a long option out of $this->_tokens. Will handle
  614. * options with an `=` in them.
  615. *
  616. * @param string $option The option to parse.
  617. * @param array $params The params to append the parsed value into
  618. * @return array Params with $option added in.
  619. */
  620. protected function _parseLongOption($option, $params)
  621. {
  622. $name = substr($option, 2);
  623. if (strpos($name, '=') !== false) {
  624. list($name, $value) = explode('=', $name, 2);
  625. array_unshift($this->_tokens, $value);
  626. }
  627. return $this->_parseOption($name, $params);
  628. }
  629. /**
  630. * Parse the value for a short option out of $this->_tokens
  631. * If the $option is a combination of multiple shortcuts like -otf
  632. * they will be shifted onto the token stack and parsed individually.
  633. *
  634. * @param string $option The option to parse.
  635. * @param array $params The params to append the parsed value into
  636. * @return array Params with $option added in.
  637. * @throws \Cake\Console\Exception\ConsoleException When unknown short options are encountered.
  638. */
  639. protected function _parseShortOption($option, $params)
  640. {
  641. $key = substr($option, 1);
  642. if (strlen($key) > 1) {
  643. $flags = str_split($key);
  644. $key = $flags[0];
  645. for ($i = 1, $len = count($flags); $i < $len; $i++) {
  646. array_unshift($this->_tokens, '-' . $flags[$i]);
  647. }
  648. }
  649. if (!isset($this->_shortOptions[$key])) {
  650. throw new ConsoleException(sprintf('Unknown short option `%s`', $key));
  651. }
  652. $name = $this->_shortOptions[$key];
  653. return $this->_parseOption($name, $params);
  654. }
  655. /**
  656. * Parse an option by its name index.
  657. *
  658. * @param string $name The name to parse.
  659. * @param array $params The params to append the parsed value into
  660. * @return array Params with $option added in.
  661. * @throws \Cake\Console\Exception\ConsoleException
  662. */
  663. protected function _parseOption($name, $params)
  664. {
  665. if (!isset($this->_options[$name])) {
  666. throw new ConsoleException(sprintf('Unknown option `%s`', $name));
  667. }
  668. $option = $this->_options[$name];
  669. $isBoolean = $option->isBoolean();
  670. $nextValue = $this->_nextToken();
  671. $emptyNextValue = (empty($nextValue) && $nextValue !== '0');
  672. if (!$isBoolean && !$emptyNextValue && !$this->_optionExists($nextValue)) {
  673. array_shift($this->_tokens);
  674. $value = $nextValue;
  675. } elseif ($isBoolean) {
  676. $value = true;
  677. } else {
  678. $value = $option->defaultValue();
  679. }
  680. if ($option->validChoice($value)) {
  681. $params[$name] = $value;
  682. return $params;
  683. }
  684. return [];
  685. }
  686. /**
  687. * Check to see if $name has an option (short/long) defined for it.
  688. *
  689. * @param string $name The name of the option.
  690. * @return bool
  691. */
  692. protected function _optionExists($name)
  693. {
  694. if (substr($name, 0, 2) === '--') {
  695. return isset($this->_options[substr($name, 2)]);
  696. }
  697. if ($name{0} === '-' && $name{1} !== '-') {
  698. return isset($this->_shortOptions[$name{1}]);
  699. }
  700. return false;
  701. }
  702. /**
  703. * Parse an argument, and ensure that the argument doesn't exceed the number of arguments
  704. * and that the argument is a valid choice.
  705. *
  706. * @param string $argument The argument to append
  707. * @param array $args The array of parsed args to append to.
  708. * @return array Args
  709. * @throws \Cake\Console\Exception\ConsoleException
  710. */
  711. protected function _parseArg($argument, $args)
  712. {
  713. if (empty($this->_args)) {
  714. $args[] = $argument;
  715. return $args;
  716. }
  717. $next = count($args);
  718. if (!isset($this->_args[$next])) {
  719. throw new ConsoleException('Too many arguments.');
  720. }
  721. if ($this->_args[$next]->validChoice($argument)) {
  722. $args[] = $argument;
  723. return $args;
  724. }
  725. }
  726. /**
  727. * Find the next token in the argv set.
  728. *
  729. * @return string next token or ''
  730. */
  731. protected function _nextToken()
  732. {
  733. return isset($this->_tokens[0]) ? $this->_tokens[0] : '';
  734. }
  735. }