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

/www/system/library/Zend/Console/Getopt.php

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