PageRenderTime 48ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/library/Zend/Console/Getopt.php

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