PageRenderTime 59ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/www/libs/Zend/Console/Getopt.php

https://bitbucket.org/Ppito/kawaiviewmodel2
PHP | 1027 lines | 550 code | 58 blank | 419 comment | 91 complexity | 4977cf8db96872d54e9e49030b5f05d1 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /**
  3. * Zend Framework (http://framework.zend.com/)
  4. *
  5. * @link http://github.com/zendframework/zf2 for the canonical source repository
  6. * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
  7. * @license http://framework.zend.com/license/new-bsd New BSD License
  8. * @package Zend_Console
  9. */
  10. namespace Zend\Console;
  11. /**
  12. * Getopt is a class to parse options for command-line
  13. * applications.
  14. *
  15. * Terminology:
  16. * Argument: an element of the argv array. This may be part of an option,
  17. * or it may be a non-option command-line argument.
  18. * Flag: the letter or word set off by a '-' or '--'. Example: in '--output filename',
  19. * '--output' is the flag.
  20. * Parameter: the additional argument that is associated with the option.
  21. * Example: in '--output filename', the 'filename' is the parameter.
  22. * Option: the combination of a flag and its parameter, if any.
  23. * Example: in '--output filename', the whole thing is the option.
  24. *
  25. * The following features are supported:
  26. *
  27. * - Short flags like '-a'. Short flags are preceded by a single
  28. * dash. Short flags may be clustered e.g. '-abc', which is the
  29. * same as '-a' '-b' '-c'.
  30. * - Long flags like '--verbose'. Long flags are preceded by a
  31. * double dash. Long flags may not be clustered.
  32. * - Options may have a parameter, e.g. '--output filename'.
  33. * - Parameters for long flags may also be set off with an equals sign,
  34. * e.g. '--output=filename'.
  35. * - Parameters for long flags may be checked as string, word, or integer.
  36. * - Automatic generation of a helpful usage message.
  37. * - Signal end of options with '--'; subsequent arguments are treated
  38. * as non-option arguments, even if they begin with '-'.
  39. * - Raise exception Zend_Console_Getopt_Exception in several cases
  40. * when invalid flags or parameters are given. Usage message is
  41. * returned in the exception object.
  42. *
  43. * The format for specifying options uses a PHP associative array.
  44. * The key is has the format of a list of pipe-separated flag names,
  45. * followed by an optional '=' to indicate a required parameter or
  46. * '-' to indicate an optional parameter. Following that, the type
  47. * of parameter may be specified as 's' for string, 'w' for word,
  48. * or 'i' for integer.
  49. *
  50. * Examples:
  51. * - 'user|username|u=s' this means '--user' or '--username' or '-u'
  52. * are synonyms, and the option requires a string parameter.
  53. * - 'p=i' this means '-p' requires an integer parameter. No synonyms.
  54. * - 'verbose|v-i' this means '--verbose' or '-v' are synonyms, and
  55. * they take an optional integer parameter.
  56. * - 'help|h' this means '--help' or '-h' are synonyms, and
  57. * they take no parameter.
  58. *
  59. * The values in the associative array are strings that are used as
  60. * brief descriptions of the options when printing a usage message.
  61. *
  62. * The simpler format for specifying options used by PHP's getopt()
  63. * function is also supported. This is similar to GNU getopt and shell
  64. * getopt format.
  65. *
  66. * Example: 'abc:' means options '-a', '-b', and '-c'
  67. * are legal, and the latter requires a string parameter.
  68. *
  69. * @category Zend
  70. * @package Zend_Console_Getopt
  71. * @version Release: @package_version@
  72. * @since Class available since Release 0.6.0
  73. *
  74. * @todo Handle flags that implicitly print usage message, e.g. --help
  75. *
  76. * @todo Enable user to specify header and footer content in the help message.
  77. *
  78. * @todo Feature request to handle option interdependencies.
  79. * e.g. if -b is specified, -a must be specified or else the
  80. * usage is invalid.
  81. *
  82. * @todo Feature request to implement callbacks.
  83. * e.g. if -a is specified, run function 'handleOptionA'().
  84. */
  85. class Getopt
  86. {
  87. /**
  88. * The options for a given application can be in multiple formats.
  89. * modeGnu is for traditional 'ab:c:' style getopt format.
  90. * modeZend is for a more structured format.
  91. */
  92. const MODE_ZEND = 'zend';
  93. const MODE_GNU = 'gnu';
  94. /**
  95. * Constant tokens for various symbols used in the mode_zend
  96. * rule format.
  97. */
  98. const PARAM_REQUIRED = '=';
  99. const PARAM_OPTIONAL = '-';
  100. const TYPE_STRING = 's';
  101. const TYPE_WORD = 'w';
  102. const TYPE_INTEGER = 'i';
  103. const TYPE_NUMERIC_FLAG = '#';
  104. /**
  105. * These are constants for optional behavior of this class.
  106. * ruleMode is either 'zend' or 'gnu' or a user-defined mode.
  107. * dashDash is true if '--' signifies the end of command-line options.
  108. * ignoreCase is true if '--opt' and '--OPT' are implicitly synonyms.
  109. * parseAll is true if all options on the command line should be parsed, regardless of
  110. * whether an argument appears before them.
  111. */
  112. const CONFIG_RULEMODE = 'ruleMode';
  113. const CONFIG_DASHDASH = 'dashDash';
  114. const CONFIG_IGNORECASE = 'ignoreCase';
  115. const CONFIG_PARSEALL = 'parseAll';
  116. const CONFIG_CUMULATIVE_PARAMETERS = 'cumulativeParameters';
  117. const CONFIG_CUMULATIVE_FLAGS = 'cumulativeFlags';
  118. const CONFIG_PARAMETER_SEPARATOR = 'parameterSeparator';
  119. const CONFIG_FREEFORM_FLAGS = 'freeformFlags';
  120. const CONFIG_NUMERIC_FLAGS = 'numericFlags';
  121. /**
  122. * Defaults for getopt configuration are:
  123. * ruleMode is 'zend' format,
  124. * dashDash (--) token is enabled,
  125. * ignoreCase is not enabled,
  126. * parseAll is enabled,
  127. * cumulative parameters are disabled,
  128. * this means that subsequent options overwrite the parameter value,
  129. * cumulative flags are disable,
  130. * freeform flags are disable.
  131. */
  132. protected $getoptConfig = array(
  133. self::CONFIG_RULEMODE => self::MODE_ZEND,
  134. self::CONFIG_DASHDASH => true,
  135. self::CONFIG_IGNORECASE => false,
  136. self::CONFIG_PARSEALL => true,
  137. self::CONFIG_CUMULATIVE_PARAMETERS => false,
  138. self::CONFIG_CUMULATIVE_FLAGS => false,
  139. self::CONFIG_PARAMETER_SEPARATOR => null,
  140. self::CONFIG_FREEFORM_FLAGS => false,
  141. self::CONFIG_NUMERIC_FLAGS => false
  142. );
  143. /**
  144. * Stores the command-line arguments for the calling application.
  145. *
  146. * @var array
  147. */
  148. protected $argv = array();
  149. /**
  150. * Stores the name of the calling application.
  151. *
  152. * @var string
  153. */
  154. protected $progname = '';
  155. /**
  156. * Stores the list of legal options for this application.
  157. *
  158. * @var array
  159. */
  160. protected $rules = array();
  161. /**
  162. * Stores alternate spellings of legal options.
  163. *
  164. * @var array
  165. */
  166. protected $ruleMap = array();
  167. /**
  168. * Stores options given by the user in the current invocation
  169. * of the application, as well as parameters given in options.
  170. *
  171. * @var array
  172. */
  173. protected $options = array();
  174. /**
  175. * Stores the command-line arguments other than options.
  176. *
  177. * @var array
  178. */
  179. protected $remainingArgs = array();
  180. /**
  181. * State of the options: parsed or not yet parsed?
  182. *
  183. * @var boolean
  184. */
  185. protected $parsed = false;
  186. /**
  187. * The constructor takes one to three parameters.
  188. *
  189. * The first parameter is $rules, which may be a string for
  190. * gnu-style format, or a structured array for Zend-style format.
  191. *
  192. * The second parameter is $argv, and it is optional. If not
  193. * specified, $argv is inferred from the global argv.
  194. *
  195. * The third parameter is an array of configuration parameters
  196. * to control the behavior of this instance of Getopt; it is optional.
  197. *
  198. * @param array $rules
  199. * @param array $argv
  200. * @param array $getoptConfig
  201. * @throws Exception\InvalidArgumentException
  202. */
  203. public function __construct($rules, $argv = null, $getoptConfig = array())
  204. {
  205. if (!isset($_SERVER['argv'])) {
  206. $errorDescription = (ini_get('register_argc_argv') == false)
  207. ? "argv is not available, because ini option 'register_argc_argv' is set Off"
  208. : '$_SERVER["argv"] is not set, but Zend_Console_Getopt cannot work without this information.';
  209. throw new Exception\InvalidArgumentException($errorDescription);
  210. }
  211. $this->progname = $_SERVER['argv'][0];
  212. $this->setOptions($getoptConfig);
  213. $this->addRules($rules);
  214. if (!is_array($argv)) {
  215. $argv = array_slice($_SERVER['argv'], 1);
  216. }
  217. if (isset($argv)) {
  218. $this->addArguments((array) $argv);
  219. }
  220. }
  221. /**
  222. * Return the state of the option seen on the command line of the
  223. * current application invocation. This function returns true, or the
  224. * parameter to the option, if any. If the option was not given,
  225. * this function returns null.
  226. *
  227. * The magic __get method works in the context of naming the option
  228. * as a virtual member of this class.
  229. *
  230. * @param string $key
  231. * @return string
  232. */
  233. public function __get($key)
  234. {
  235. return $this->getOption($key);
  236. }
  237. /**
  238. * Test whether a given option has been seen.
  239. *
  240. * @param string $key
  241. * @return boolean
  242. */
  243. public function __isset($key)
  244. {
  245. $this->parse();
  246. if (isset($this->ruleMap[$key])) {
  247. $key = $this->ruleMap[$key];
  248. return isset($this->options[$key]);
  249. }
  250. return false;
  251. }
  252. /**
  253. * Set the value for a given option.
  254. *
  255. * @param string $key
  256. * @param string $value
  257. * @return void
  258. */
  259. public function __set($key, $value)
  260. {
  261. $this->parse();
  262. if (isset($this->ruleMap[$key])) {
  263. $key = $this->ruleMap[$key];
  264. $this->options[$key] = $value;
  265. }
  266. }
  267. /**
  268. * Return the current set of options and parameters seen as a string.
  269. *
  270. * @return string
  271. */
  272. public function __toString()
  273. {
  274. return $this->toString();
  275. }
  276. /**
  277. * Unset an option.
  278. *
  279. * @param string $key
  280. * @return void
  281. */
  282. public function __unset($key)
  283. {
  284. $this->parse();
  285. if (isset($this->ruleMap[$key])) {
  286. $key = $this->ruleMap[$key];
  287. unset($this->options[$key]);
  288. }
  289. }
  290. /**
  291. * Define additional command-line arguments.
  292. * These are appended to those defined when the constructor was called.
  293. *
  294. * @param array $argv
  295. * @throws \Zend\Console\Exception\InvalidArgumentException When not given an array as parameter
  296. * @return \Zend\Console\Getopt Provides a fluent interface
  297. */
  298. public function addArguments($argv)
  299. {
  300. if (!is_array($argv)) {
  301. throw new Exception\InvalidArgumentException("Parameter #1 to addArguments should be an array");
  302. }
  303. $this->argv = array_merge($this->argv, $argv);
  304. $this->parsed = false;
  305. return $this;
  306. }
  307. /**
  308. * Define full set of command-line arguments.
  309. * These replace any currently defined.
  310. *
  311. * @param array $argv
  312. * @throws \Zend\Console\Exception\InvalidArgumentException When not given an array as parameter
  313. * @return \Zend\Console\Getopt Provides a fluent interface
  314. */
  315. public function setArguments($argv)
  316. {
  317. if (!is_array($argv)) {
  318. throw new Exception\InvalidArgumentException("Parameter #1 to setArguments should be an array");
  319. }
  320. $this->argv = $argv;
  321. $this->parsed = false;
  322. return $this;
  323. }
  324. /**
  325. * Define multiple configuration options from an associative array.
  326. * These are not program options, but properties to configure
  327. * the behavior of Zend_Console_Getopt.
  328. *
  329. * @param array $getoptConfig
  330. * @return \Zend\Console\Getopt Provides a fluent interface
  331. */
  332. public function setOptions($getoptConfig)
  333. {
  334. if (isset($getoptConfig)) {
  335. foreach ($getoptConfig as $key => $value) {
  336. $this->setOption($key, $value);
  337. }
  338. }
  339. return $this;
  340. }
  341. /**
  342. * Define one configuration option as a key/value pair.
  343. * These are not program options, but properties to configure
  344. * the behavior of Zend_Console_Getopt.
  345. *
  346. * @param string $configKey
  347. * @param string $configValue
  348. * @return \Zend\Console\Getopt Provides a fluent interface
  349. */
  350. public function setOption($configKey, $configValue)
  351. {
  352. if ($configKey !== null) {
  353. $this->getoptConfig[$configKey] = $configValue;
  354. }
  355. return $this;
  356. }
  357. /**
  358. * Define additional option rules.
  359. * These are appended to the rules defined when the constructor was called.
  360. *
  361. * @param array $rules
  362. * @return \Zend\Console\Getopt Provides a fluent interface
  363. */
  364. public function addRules($rules)
  365. {
  366. $ruleMode = $this->getoptConfig['ruleMode'];
  367. switch ($this->getoptConfig['ruleMode']) {
  368. case self::MODE_ZEND:
  369. if (is_array($rules)) {
  370. $this->_addRulesModeZend($rules);
  371. break;
  372. }
  373. // intentional fallthrough
  374. case self::MODE_GNU:
  375. $this->_addRulesModeGnu($rules);
  376. break;
  377. default:
  378. /**
  379. * Call addRulesModeFoo() for ruleMode 'foo'.
  380. * The developer should subclass Getopt and
  381. * provide this method.
  382. */
  383. $method = '_addRulesMode' . ucfirst($ruleMode);
  384. $this->$method($rules);
  385. }
  386. $this->parsed = false;
  387. return $this;
  388. }
  389. /**
  390. * Return the current set of options and parameters seen as a string.
  391. *
  392. * @return string
  393. */
  394. public function toString()
  395. {
  396. $this->parse();
  397. $s = array();
  398. foreach ($this->options as $flag => $value) {
  399. $s[] = $flag . '=' . ($value === true ? 'true' : $value);
  400. }
  401. return implode(' ', $s);
  402. }
  403. /**
  404. * Return the current set of options and parameters seen
  405. * as an array of canonical options and parameters.
  406. *
  407. * Clusters have been expanded, and option aliases
  408. * have been mapped to their primary option names.
  409. *
  410. * @return array
  411. */
  412. public function toArray()
  413. {
  414. $this->parse();
  415. $s = array();
  416. foreach ($this->options as $flag => $value) {
  417. $s[] = $flag;
  418. if ($value !== true) {
  419. $s[] = $value;
  420. }
  421. }
  422. return $s;
  423. }
  424. /**
  425. * Return the current set of options and parameters seen in Json format.
  426. *
  427. * @return string
  428. */
  429. public function toJson()
  430. {
  431. $this->parse();
  432. $j = array();
  433. foreach ($this->options as $flag => $value) {
  434. $j['options'][] = array(
  435. 'option' => array(
  436. 'flag' => $flag,
  437. 'parameter' => $value
  438. )
  439. );
  440. }
  441. $json = \Zend\Json\Json::encode($j);
  442. return $json;
  443. }
  444. /**
  445. * Return the current set of options and parameters seen in XML format.
  446. *
  447. * @return string
  448. */
  449. public function toXml()
  450. {
  451. $this->parse();
  452. $doc = new \DomDocument('1.0', 'utf-8');
  453. $optionsNode = $doc->createElement('options');
  454. $doc->appendChild($optionsNode);
  455. foreach ($this->options as $flag => $value) {
  456. $optionNode = $doc->createElement('option');
  457. $optionNode->setAttribute('flag', utf8_encode($flag));
  458. if ($value !== true) {
  459. $optionNode->setAttribute('parameter', utf8_encode($value));
  460. }
  461. $optionsNode->appendChild($optionNode);
  462. }
  463. $xml = $doc->saveXML();
  464. return $xml;
  465. }
  466. /**
  467. * Return a list of options that have been seen in the current argv.
  468. *
  469. * @return array
  470. */
  471. public function getOptions()
  472. {
  473. $this->parse();
  474. return array_keys($this->options);
  475. }
  476. /**
  477. * Return the state of the option seen on the command line of the
  478. * current application invocation.
  479. *
  480. * This function returns true, or the parameter value to the option, if any.
  481. * If the option was not given, this function returns false.
  482. *
  483. * @param string $flag
  484. * @return mixed
  485. */
  486. public function getOption($flag)
  487. {
  488. $this->parse();
  489. if ($this->getoptConfig[self::CONFIG_IGNORECASE]) {
  490. $flag = strtolower($flag);
  491. }
  492. if (isset($this->ruleMap[$flag])) {
  493. $flag = $this->ruleMap[$flag];
  494. if (isset($this->options[$flag])) {
  495. return $this->options[$flag];
  496. }
  497. }
  498. return null;
  499. }
  500. /**
  501. * Return the arguments from the command-line following all options found.
  502. *
  503. * @return array
  504. */
  505. public function getRemainingArgs()
  506. {
  507. $this->parse();
  508. return $this->remainingArgs;
  509. }
  510. public function getArguments()
  511. {
  512. $result = $this->getRemainingArgs();
  513. foreach ($this->getOptions() as $option) {
  514. $result[$option] = $this->getOption($option);
  515. }
  516. return $result;
  517. }
  518. /**
  519. * Return a useful option reference, formatted for display in an
  520. * error message.
  521. *
  522. * Note that this usage information is provided in most Exceptions
  523. * generated by this class.
  524. *
  525. * @return string
  526. */
  527. public function getUsageMessage()
  528. {
  529. $usage = "Usage: {$this->progname} [ options ]\n";
  530. $maxLen = 20;
  531. $lines = array();
  532. foreach ($this->rules as $rule) {
  533. if (isset($rule['isFreeformFlag'])) {
  534. continue;
  535. }
  536. $flags = array();
  537. if (is_array($rule['alias'])) {
  538. foreach ($rule['alias'] as $flag) {
  539. $flags[] = (strlen($flag) == 1 ? '-' : '--') . $flag;
  540. }
  541. }
  542. $linepart['name'] = implode('|', $flags);
  543. if (isset($rule['param']) && $rule['param'] != 'none') {
  544. $linepart['name'] .= ' ';
  545. switch ($rule['param']) {
  546. case 'optional':
  547. $linepart['name'] .= "[ <{$rule['paramType']}> ]";
  548. break;
  549. case 'required':
  550. $linepart['name'] .= "<{$rule['paramType']}>";
  551. break;
  552. }
  553. }
  554. if (strlen($linepart['name']) > $maxLen) {
  555. $maxLen = strlen($linepart['name']);
  556. }
  557. $linepart['help'] = '';
  558. if (isset($rule['help'])) {
  559. $linepart['help'] .= $rule['help'];
  560. }
  561. $lines[] = $linepart;
  562. }
  563. foreach ($lines as $linepart) {
  564. $usage .= sprintf("%s %s\n",
  565. str_pad($linepart['name'], $maxLen),
  566. $linepart['help']);
  567. }
  568. return $usage;
  569. }
  570. /**
  571. * Define aliases for options.
  572. *
  573. * The parameter $aliasMap is an associative array
  574. * mapping option name (short or long) to an alias.
  575. *
  576. * @param array $aliasMap
  577. * @throws \Zend\Console\Exception\ExceptionInterface
  578. * @return \Zend\Console\Getopt Provides a fluent interface
  579. */
  580. public function setAliases($aliasMap)
  581. {
  582. foreach ($aliasMap as $flag => $alias) {
  583. if ($this->getoptConfig[self::CONFIG_IGNORECASE]) {
  584. $flag = strtolower($flag);
  585. $alias = strtolower($alias);
  586. }
  587. if (!isset($this->ruleMap[$flag])) {
  588. continue;
  589. }
  590. $flag = $this->ruleMap[$flag];
  591. if (isset($this->rules[$alias]) || isset($this->ruleMap[$alias])) {
  592. $o = (strlen($alias) == 1 ? '-' : '--') . $alias;
  593. throw new Exception\InvalidArgumentException("Option \"$o\" is being defined more than once.");
  594. }
  595. $this->rules[$flag]['alias'][] = $alias;
  596. $this->ruleMap[$alias] = $flag;
  597. }
  598. return $this;
  599. }
  600. /**
  601. * Define help messages for options.
  602. *
  603. * The parameter $help_map is an associative array
  604. * mapping option name (short or long) to the help string.
  605. *
  606. * @param array $helpMap
  607. * @return \Zend\Console\Getopt Provides a fluent interface
  608. */
  609. public function setHelp($helpMap)
  610. {
  611. foreach ($helpMap as $flag => $help) {
  612. if (!isset($this->ruleMap[$flag])) {
  613. continue;
  614. }
  615. $flag = $this->ruleMap[$flag];
  616. $this->rules[$flag]['help'] = $help;
  617. }
  618. return $this;
  619. }
  620. /**
  621. * Parse command-line arguments and find both long and short
  622. * options.
  623. *
  624. * Also find option parameters, and remaining arguments after
  625. * all options have been parsed.
  626. *
  627. * @return \Zend\Console\Getopt|null Provides a fluent interface
  628. */
  629. public function parse()
  630. {
  631. if ($this->parsed === true) {
  632. return;
  633. }
  634. $argv = $this->argv;
  635. $this->options = array();
  636. $this->remainingArgs = array();
  637. while (count($argv) > 0) {
  638. if ($argv[0] == '--') {
  639. array_shift($argv);
  640. if ($this->getoptConfig[self::CONFIG_DASHDASH]) {
  641. $this->remainingArgs = array_merge($this->remainingArgs, $argv);
  642. break;
  643. }
  644. }
  645. if (substr($argv[0], 0, 2) == '--') {
  646. $this->_parseLongOption($argv);
  647. } elseif (substr($argv[0], 0, 1) == '-' && ('-' != $argv[0] || count($argv) >1)) {
  648. $this->_parseShortOptionCluster($argv);
  649. } elseif ($this->getoptConfig[self::CONFIG_PARSEALL]) {
  650. $this->remainingArgs[] = array_shift($argv);
  651. } else {
  652. /*
  653. * We should put all other arguments in remainingArgs and stop parsing
  654. * since CONFIG_PARSEALL is false.
  655. */
  656. $this->remainingArgs = array_merge($this->remainingArgs, $argv);
  657. break;
  658. }
  659. }
  660. $this->parsed = true;
  661. return $this;
  662. }
  663. /**
  664. * Parse command-line arguments for a single long option.
  665. * A long option is preceded by a double '--' character.
  666. * Long options may not be clustered.
  667. *
  668. * @param mixed &$argv
  669. * @return void
  670. */
  671. protected function _parseLongOption(&$argv)
  672. {
  673. $optionWithParam = ltrim(array_shift($argv), '-');
  674. $l = explode('=', $optionWithParam, 2);
  675. $flag = array_shift($l);
  676. $param = array_shift($l);
  677. if (isset($param)) {
  678. array_unshift($argv, $param);
  679. }
  680. $this->_parseSingleOption($flag, $argv);
  681. }
  682. /**
  683. * Parse command-line arguments for short options.
  684. * Short options are those preceded by a single '-' character.
  685. * Short options may be clustered.
  686. *
  687. * @param mixed &$argv
  688. * @return void
  689. */
  690. protected function _parseShortOptionCluster(&$argv)
  691. {
  692. $flagCluster = ltrim(array_shift($argv), '-');
  693. foreach (str_split($flagCluster) as $flag) {
  694. $this->_parseSingleOption($flag, $argv);
  695. }
  696. }
  697. /**
  698. * Parse command-line arguments for a single option.
  699. *
  700. * @param string $flag
  701. * @param mixed $argv
  702. * @throws \Zend\Console\Exception\ExceptionInterface
  703. * @return void
  704. */
  705. protected function _parseSingleOption($flag, &$argv)
  706. {
  707. if ($this->getoptConfig[self::CONFIG_IGNORECASE]) {
  708. $flag = strtolower($flag);
  709. }
  710. // Check if this option is numeric one
  711. if (preg_match('/^\d+$/', $flag)) {
  712. return $this->_setNumericOptionValue($flag);
  713. }
  714. if (!isset($this->ruleMap[$flag])) {
  715. // Don't throw Exception for flag-like param in case when freeform flags are allowed
  716. if (!$this->getoptConfig[self::CONFIG_FREEFORM_FLAGS]) {
  717. throw new Exception\RuntimeException(
  718. "Option \"$flag\" is not recognized.",
  719. $this->getUsageMessage()
  720. );
  721. }
  722. // Magic methods in future will use this mark as real flag value
  723. $this->ruleMap[$flag] = $flag;
  724. $realFlag = $flag;
  725. $this->rules[$realFlag] = array(
  726. 'param' => 'optional',
  727. 'isFreeformFlag' => true
  728. );
  729. } else {
  730. $realFlag = $this->ruleMap[$flag];
  731. }
  732. switch ($this->rules[$realFlag]['param']) {
  733. case 'required':
  734. if (count($argv) > 0) {
  735. $param = array_shift($argv);
  736. $this->_checkParameterType($realFlag, $param);
  737. } else {
  738. throw new Exception\RuntimeException(
  739. "Option \"$flag\" requires a parameter.",
  740. $this->getUsageMessage()
  741. );
  742. }
  743. break;
  744. case 'optional':
  745. if (count($argv) > 0 && substr($argv[0], 0, 1) != '-') {
  746. $param = array_shift($argv);
  747. $this->_checkParameterType($realFlag, $param);
  748. } else {
  749. $param = true;
  750. }
  751. break;
  752. default:
  753. $param = true;
  754. }
  755. $this->_setSingleOptionValue($realFlag, $param);
  756. }
  757. /**
  758. * Set given value as value of numeric option
  759. *
  760. * Throw runtime exception if this action is deny by configuration
  761. * or no one numeric option handlers is defined
  762. *
  763. * @param int $value
  764. * @throws Exception\RuntimeException
  765. * @return void
  766. */
  767. protected function _setNumericOptionValue($value)
  768. {
  769. if (!$this->getoptConfig[self::CONFIG_NUMERIC_FLAGS]) {
  770. throw new Exception\RuntimeException("Using of numeric flags are deny by configuration");
  771. }
  772. if (empty($this->getoptConfig['numericFlagsOption'])) {
  773. throw new Exception\RuntimeException("Any option for handling numeric flags are specified");
  774. }
  775. return $this->_setSingleOptionValue($this->getoptConfig['numericFlagsOption'], $value);
  776. }
  777. /**
  778. * Add relative to options' flag value
  779. *
  780. * If options list already has current flag as key
  781. * and parser should follow cumulative params by configuration,
  782. * we should to add new param to array, not to overwrite
  783. *
  784. * @param string $flag
  785. * @param string $value
  786. * @return null
  787. */
  788. protected function _setSingleOptionValue($flag, $value)
  789. {
  790. if (true === $value && $this->getoptConfig[self::CONFIG_CUMULATIVE_FLAGS]) {
  791. // For boolean values we have to create new flag, or increase number of flags' usage count
  792. return $this->_setBooleanFlagValue($flag);
  793. }
  794. // Split multiple values, if necessary
  795. // Filter empty values from splited array
  796. $separator = $this->getoptConfig[self::CONFIG_PARAMETER_SEPARATOR];
  797. if (is_string($value) && !empty($separator) && is_string($separator) && substr_count($value, $separator)) {
  798. $value = array_filter(explode($separator, $value));
  799. }
  800. if (!array_key_exists($flag, $this->options)) {
  801. $this->options[$flag] = $value;
  802. } elseif ($this->getoptConfig[self::CONFIG_CUMULATIVE_PARAMETERS]) {
  803. $this->options[$flag] = (array) $this->options[$flag];
  804. array_push($this->options[$flag], $value);
  805. } else {
  806. $this->options[$flag] = $value;
  807. }
  808. }
  809. /**
  810. * Set TRUE value to given flag, if this option does not exist yet
  811. * In other case increase value to show count of flags' usage
  812. *
  813. * @param string $flag
  814. * @return null
  815. */
  816. protected function _setBooleanFlagValue($flag)
  817. {
  818. $this->options[$flag] = array_key_exists($flag, $this->options)
  819. ? (int) $this->options[$flag] + 1
  820. : true;
  821. }
  822. /**
  823. * Return true if the parameter is in a valid format for
  824. * the option $flag.
  825. * Throw an exception in most other cases.
  826. *
  827. * @param string $flag
  828. * @param string $param
  829. * @throws \Zend\Console\Exception\ExceptionInterface
  830. * @return bool
  831. */
  832. protected function _checkParameterType($flag, $param)
  833. {
  834. $type = 'string';
  835. if (isset($this->rules[$flag]['paramType'])) {
  836. $type = $this->rules[$flag]['paramType'];
  837. }
  838. switch ($type) {
  839. case 'word':
  840. if (preg_match('/\W/', $param)) {
  841. throw new Exception\RuntimeException(
  842. "Option \"$flag\" requires a single-word parameter, but was given \"$param\".",
  843. $this->getUsageMessage());
  844. }
  845. break;
  846. case 'integer':
  847. if (preg_match('/\D/', $param)) {
  848. throw new Exception\RuntimeException(
  849. "Option \"$flag\" requires an integer parameter, but was given \"$param\".",
  850. $this->getUsageMessage());
  851. }
  852. break;
  853. case 'string':
  854. default:
  855. break;
  856. }
  857. return true;
  858. }
  859. /**
  860. * Define legal options using the gnu-style format.
  861. *
  862. * @param string $rules
  863. * @return void
  864. */
  865. protected function _addRulesModeGnu($rules)
  866. {
  867. $ruleArray = array();
  868. /**
  869. * Options may be single alphanumeric characters.
  870. * Options may have a ':' which indicates a required string parameter.
  871. * No long options or option aliases are supported in GNU style.
  872. */
  873. preg_match_all('/([a-zA-Z0-9]:?)/', $rules, $ruleArray);
  874. foreach ($ruleArray[1] as $rule) {
  875. $r = array();
  876. $flag = substr($rule, 0, 1);
  877. if ($this->getoptConfig[self::CONFIG_IGNORECASE]) {
  878. $flag = strtolower($flag);
  879. }
  880. $r['alias'][] = $flag;
  881. if (substr($rule, 1, 1) == ':') {
  882. $r['param'] = 'required';
  883. $r['paramType'] = 'string';
  884. } else {
  885. $r['param'] = 'none';
  886. }
  887. $this->rules[$flag] = $r;
  888. $this->ruleMap[$flag] = $flag;
  889. }
  890. }
  891. /**
  892. * Define legal options using the Zend-style format.
  893. *
  894. * @param array $rules
  895. * @throws \Zend\Console\Exception\ExceptionInterface
  896. * @return void
  897. */
  898. protected function _addRulesModeZend($rules)
  899. {
  900. foreach ($rules as $ruleCode => $helpMessage) {
  901. // this may have to translate the long parm type if there
  902. // are any complaints that =string will not work (even though that use
  903. // case is not documented)
  904. if (in_array(substr($ruleCode, -2, 1), array('-', '='))) {
  905. $flagList = substr($ruleCode, 0, -2);
  906. $delimiter = substr($ruleCode, -2, 1);
  907. $paramType = substr($ruleCode, -1);
  908. } else {
  909. $flagList = $ruleCode;
  910. $delimiter = $paramType = null;
  911. }
  912. if ($this->getoptConfig[self::CONFIG_IGNORECASE]) {
  913. $flagList = strtolower($flagList);
  914. }
  915. $flags = explode('|', $flagList);
  916. $rule = array();
  917. $mainFlag = $flags[0];
  918. foreach ($flags as $flag) {
  919. if (empty($flag)) {
  920. throw new Exception\InvalidArgumentException("Blank flag not allowed in rule \"$ruleCode\".");
  921. }
  922. if (strlen($flag) == 1) {
  923. if (isset($this->ruleMap[$flag])) {
  924. throw new Exception\InvalidArgumentException(
  925. "Option \"-$flag\" is being defined more than once.");
  926. }
  927. $this->ruleMap[$flag] = $mainFlag;
  928. $rule['alias'][] = $flag;
  929. } else {
  930. if (isset($this->rules[$flag]) || isset($this->ruleMap[$flag])) {
  931. throw new Exception\InvalidArgumentException(
  932. "Option \"--$flag\" is being defined more than once.");
  933. }
  934. $this->ruleMap[$flag] = $mainFlag;
  935. $rule['alias'][] = $flag;
  936. }
  937. }
  938. if (isset($delimiter)) {
  939. switch ($delimiter) {
  940. case self::PARAM_REQUIRED:
  941. $rule['param'] = 'required';
  942. break;
  943. case self::PARAM_OPTIONAL:
  944. default:
  945. $rule['param'] = 'optional';
  946. }
  947. switch (substr($paramType, 0, 1)) {
  948. case self::TYPE_WORD:
  949. $rule['paramType'] = 'word';
  950. break;
  951. case self::TYPE_INTEGER:
  952. $rule['paramType'] = 'integer';
  953. break;
  954. case self::TYPE_NUMERIC_FLAG:
  955. $rule['paramType'] = 'numericFlag';
  956. $this->getoptConfig['numericFlagsOption'] = $mainFlag;
  957. break;
  958. case self::TYPE_STRING:
  959. default:
  960. $rule['paramType'] = 'string';
  961. }
  962. } else {
  963. $rule['param'] = 'none';
  964. }
  965. $rule['help'] = $helpMessage;
  966. $this->rules[$mainFlag] = $rule;
  967. }
  968. }
  969. }