PageRenderTime 65ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/scalr-2/tags/scalr-2.0.0/app/src/Lib/ZF/Zend/Console/Getopt.php

http://scalr.googlecode.com/
PHP | 957 lines | 488 code | 45 blank | 424 comment | 80 complexity | 02f45a7ce34797d456dc75bf198c2349 MD5 | raw file
Possible License(s): LGPL-2.1, Apache-2.0, GPL-3.0
  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-2009 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 16971 2009-07-22 18:05:45Z mikaelkael $
  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-2009 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. require_once 'Zend/Console/Getopt/Exception.php';
  233. if (ini_get('register_argc_argv') == false) {
  234. throw new Zend_Console_Getopt_Exception(
  235. "argv is not available, because ini option 'register_argc_argv' is set Off"
  236. );
  237. } else {
  238. throw new Zend_Console_Getopt_Exception(
  239. '$_SERVER["argv"] is not set, but Zend_Console_Getopt cannot work without this information.'
  240. );
  241. }
  242. }
  243. $this->_progname = $_SERVER['argv'][0];
  244. $this->setOptions($getoptConfig);
  245. $this->addRules($rules);
  246. if (!is_array($argv)) {
  247. $argv = array_slice($_SERVER['argv'], 1);
  248. }
  249. if (isset($argv)) {
  250. $this->addArguments((array)$argv);
  251. }
  252. }
  253. /**
  254. * Return the state of the option seen on the command line of the
  255. * current application invocation. This function returns true, or the
  256. * parameter to the option, if any. If the option was not given,
  257. * this function returns null.
  258. *
  259. * The magic __get method works in the context of naming the option
  260. * as a virtual member of this class.
  261. *
  262. * @param string $key
  263. * @return string
  264. */
  265. public function __get($key)
  266. {
  267. return $this->getOption($key);
  268. }
  269. /**
  270. * Test whether a given option has been seen.
  271. *
  272. * @param string $key
  273. * @return boolean
  274. */
  275. public function __isset($key)
  276. {
  277. $this->parse();
  278. if (isset($this->_ruleMap[$key])) {
  279. $key = $this->_ruleMap[$key];
  280. return isset($this->_options[$key]);
  281. }
  282. return false;
  283. }
  284. /**
  285. * Set the value for a given option.
  286. *
  287. * @param string $key
  288. * @param string $value
  289. * @return void
  290. */
  291. public function __set($key, $value)
  292. {
  293. $this->parse();
  294. if (isset($this->_ruleMap[$key])) {
  295. $key = $this->_ruleMap[$key];
  296. $this->_options[$key] = $value;
  297. }
  298. }
  299. /**
  300. * Return the current set of options and parameters seen as a string.
  301. *
  302. * @return string
  303. */
  304. public function __toString()
  305. {
  306. return $this->toString();
  307. }
  308. /**
  309. * Unset an option.
  310. *
  311. * @param string $key
  312. * @return void
  313. */
  314. public function __unset($key)
  315. {
  316. $this->parse();
  317. if (isset($this->_ruleMap[$key])) {
  318. $key = $this->_ruleMap[$key];
  319. unset($this->_options[$key]);
  320. }
  321. }
  322. /**
  323. * Define additional command-line arguments.
  324. * These are appended to those defined when the constructor was called.
  325. *
  326. * @param array $argv
  327. * @return Zend_Console_Getopt Provides a fluent interface
  328. */
  329. public function addArguments($argv)
  330. {
  331. $this->_argv = array_merge($this->_argv, $argv);
  332. $this->_parsed = false;
  333. return $this;
  334. }
  335. /**
  336. * Define full set of command-line arguments.
  337. * These replace any currently defined.
  338. *
  339. * @param array $argv
  340. * @return Zend_Console_Getopt Provides a fluent interface
  341. */
  342. public function setArguments($argv)
  343. {
  344. $this->_argv = $argv;
  345. $this->_parsed = false;
  346. return $this;
  347. }
  348. /**
  349. * Define multiple configuration options from an associative array.
  350. * These are not program options, but properties to configure
  351. * the behavior of Zend_Console_Getopt.
  352. *
  353. * @param array $getoptConfig
  354. * @return Zend_Console_Getopt Provides a fluent interface
  355. */
  356. public function setOptions($getoptConfig)
  357. {
  358. if (isset($getoptConfig)) {
  359. foreach ($getoptConfig as $key => $value) {
  360. $this->setOption($key, $value);
  361. }
  362. }
  363. return $this;
  364. }
  365. /**
  366. * Define one configuration option as a key/value pair.
  367. * These are not program options, but properties to configure
  368. * the behavior of Zend_Console_Getopt.
  369. *
  370. * @param string $configKey
  371. * @param string $configValue
  372. * @return Zend_Console_Getopt Provides a fluent interface
  373. */
  374. public function setOption($configKey, $configValue)
  375. {
  376. if ($configKey !== null) {
  377. $this->_getoptConfig[$configKey] = $configValue;
  378. }
  379. return $this;
  380. }
  381. /**
  382. * Define additional option rules.
  383. * These are appended to the rules defined when the constructor was called.
  384. *
  385. * @param array $rules
  386. * @return Zend_Console_Getopt Provides a fluent interface
  387. */
  388. public function addRules($rules)
  389. {
  390. $ruleMode = $this->_getoptConfig['ruleMode'];
  391. switch ($this->_getoptConfig['ruleMode']) {
  392. case self::MODE_ZEND:
  393. if (is_array($rules)) {
  394. $this->_addRulesModeZend($rules);
  395. break;
  396. }
  397. // intentional fallthrough
  398. case self::MODE_GNU:
  399. $this->_addRulesModeGnu($rules);
  400. break;
  401. default:
  402. /**
  403. * Call addRulesModeFoo() for ruleMode 'foo'.
  404. * The developer should subclass Getopt and
  405. * provide this method.
  406. */
  407. $method = '_addRulesMode' . ucfirst($ruleMode);
  408. $this->$method($rules);
  409. }
  410. $this->_parsed = false;
  411. return $this;
  412. }
  413. /**
  414. * Return the current set of options and parameters seen as a string.
  415. *
  416. * @return string
  417. */
  418. public function toString()
  419. {
  420. $this->parse();
  421. $s = array();
  422. foreach ($this->_options as $flag => $value) {
  423. $s[] = $flag . '=' . ($value === true ? 'true' : $value);
  424. }
  425. return implode(' ', $s);
  426. }
  427. /**
  428. * Return the current set of options and parameters seen
  429. * as an array of canonical options and parameters.
  430. *
  431. * Clusters have been expanded, and option aliases
  432. * have been mapped to their primary option names.
  433. *
  434. * @return array
  435. */
  436. public function toArray()
  437. {
  438. $this->parse();
  439. $s = array();
  440. foreach ($this->_options as $flag => $value) {
  441. $s[] = $flag;
  442. if ($value !== true) {
  443. $s[] = $value;
  444. }
  445. }
  446. return $s;
  447. }
  448. /**
  449. * Return the current set of options and parameters seen in Json format.
  450. *
  451. * @return string
  452. */
  453. public function toJson()
  454. {
  455. $this->parse();
  456. $j = array();
  457. foreach ($this->_options as $flag => $value) {
  458. $j['options'][] = array(
  459. 'option' => array(
  460. 'flag' => $flag,
  461. 'parameter' => $value
  462. )
  463. );
  464. }
  465. /**
  466. * @see Zend_Json
  467. */
  468. require_once 'Zend/Json.php';
  469. $json = Zend_Json::encode($j);
  470. return $json;
  471. }
  472. /**
  473. * Return the current set of options and parameters seen in XML format.
  474. *
  475. * @return string
  476. */
  477. public function toXml()
  478. {
  479. $this->parse();
  480. $doc = new DomDocument('1.0', 'utf-8');
  481. $optionsNode = $doc->createElement('options');
  482. $doc->appendChild($optionsNode);
  483. foreach ($this->_options as $flag => $value) {
  484. $optionNode = $doc->createElement('option');
  485. $optionNode->setAttribute('flag', utf8_encode($flag));
  486. if ($value !== true) {
  487. $optionNode->setAttribute('parameter', utf8_encode($value));
  488. }
  489. $optionsNode->appendChild($optionNode);
  490. }
  491. $xml = $doc->saveXML();
  492. return $xml;
  493. }
  494. /**
  495. * Return a list of options that have been seen in the current argv.
  496. *
  497. * @return array
  498. */
  499. public function getOptions()
  500. {
  501. $this->parse();
  502. return array_keys($this->_options);
  503. }
  504. /**
  505. * Return the state of the option seen on the command line of the
  506. * current application invocation.
  507. *
  508. * This function returns true, or the parameter value to the option, if any.
  509. * If the option was not given, this function returns false.
  510. *
  511. * @param string $flag
  512. * @return mixed
  513. */
  514. public function getOption($flag)
  515. {
  516. $this->parse();
  517. if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
  518. $flag = strtolower($flag);
  519. }
  520. if (isset($this->_ruleMap[$flag])) {
  521. $flag = $this->_ruleMap[$flag];
  522. if (isset($this->_options[$flag])) {
  523. return $this->_options[$flag];
  524. }
  525. }
  526. return null;
  527. }
  528. /**
  529. * Return the arguments from the command-line following all options found.
  530. *
  531. * @return array
  532. */
  533. public function getRemainingArgs()
  534. {
  535. $this->parse();
  536. return $this->_remainingArgs;
  537. }
  538. /**
  539. * Return a useful option reference, formatted for display in an
  540. * error message.
  541. *
  542. * Note that this usage information is provided in most Exceptions
  543. * generated by this class.
  544. *
  545. * @return string
  546. */
  547. public function getUsageMessage()
  548. {
  549. $usage = "Usage: {$this->_progname} [ options ]\n";
  550. $maxLen = 20;
  551. foreach ($this->_rules as $rule) {
  552. $flags = array();
  553. if (is_array($rule['alias'])) {
  554. foreach ($rule['alias'] as $flag) {
  555. $flags[] = (strlen($flag) == 1 ? '-' : '--') . $flag;
  556. }
  557. }
  558. $linepart['name'] = implode('|', $flags);
  559. if (isset($rule['param']) && $rule['param'] != 'none') {
  560. $linepart['name'] .= ' ';
  561. switch ($rule['param']) {
  562. case 'optional':
  563. $linepart['name'] .= "[ <{$rule['paramType']}> ]";
  564. break;
  565. case 'required':
  566. $linepart['name'] .= "<{$rule['paramType']}>";
  567. break;
  568. }
  569. }
  570. if (strlen($linepart['name']) > $maxLen) {
  571. $maxLen = strlen($linepart['name']);
  572. }
  573. $linepart['help'] = '';
  574. if (isset($rule['help'])) {
  575. $linepart['help'] .= $rule['help'];
  576. }
  577. $lines[] = $linepart;
  578. }
  579. foreach ($lines as $linepart) {
  580. $usage .= sprintf("%s %s\n",
  581. str_pad($linepart['name'], $maxLen),
  582. $linepart['help']);
  583. }
  584. return $usage;
  585. }
  586. /**
  587. * Define aliases for options.
  588. *
  589. * The parameter $aliasMap is an associative array
  590. * mapping option name (short or long) to an alias.
  591. *
  592. * @param array $aliasMap
  593. * @throws Zend_Console_Getopt_Exception
  594. * @return Zend_Console_Getopt Provides a fluent interface
  595. */
  596. public function setAliases($aliasMap)
  597. {
  598. foreach ($aliasMap as $flag => $alias)
  599. {
  600. if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
  601. $flag = strtolower($flag);
  602. $alias = strtolower($alias);
  603. }
  604. if (!isset($this->_ruleMap[$flag])) {
  605. continue;
  606. }
  607. $flag = $this->_ruleMap[$flag];
  608. if (isset($this->_rules[$alias]) || isset($this->_ruleMap[$alias])) {
  609. $o = (strlen($alias) == 1 ? '-' : '--') . $alias;
  610. require_once 'Zend/Console/Getopt/Exception.php';
  611. throw new Zend_Console_Getopt_Exception(
  612. "Option \"$o\" is being defined more than once.");
  613. }
  614. $this->_rules[$flag]['alias'][] = $alias;
  615. $this->_ruleMap[$alias] = $flag;
  616. }
  617. return $this;
  618. }
  619. /**
  620. * Define help messages for options.
  621. *
  622. * The parameter $help_map is an associative array
  623. * mapping option name (short or long) to the help string.
  624. *
  625. * @param array $helpMap
  626. * @return Zend_Console_Getopt Provides a fluent interface
  627. */
  628. public function setHelp($helpMap)
  629. {
  630. foreach ($helpMap as $flag => $help)
  631. {
  632. if (!isset($this->_ruleMap[$flag])) {
  633. continue;
  634. }
  635. $flag = $this->_ruleMap[$flag];
  636. $this->_rules[$flag]['help'] = $help;
  637. }
  638. return $this;
  639. }
  640. /**
  641. * Parse command-line arguments and find both long and short
  642. * options.
  643. *
  644. * Also find option parameters, and remaining arguments after
  645. * all options have been parsed.
  646. *
  647. * @return Zend_Console_Getopt|null Provides a fluent interface
  648. */
  649. public function parse()
  650. {
  651. if ($this->_parsed === true) {
  652. return;
  653. }
  654. $argv = $this->_argv;
  655. $this->_options = array();
  656. $this->_remainingArgs = array();
  657. while (count($argv) > 0) {
  658. if ($argv[0] == '--') {
  659. array_shift($argv);
  660. if ($this->_getoptConfig[self::CONFIG_DASHDASH]) {
  661. $this->_remainingArgs = array_merge($this->_remainingArgs, $argv);
  662. break;
  663. }
  664. }
  665. if (substr($argv[0], 0, 2) == '--') {
  666. $this->_parseLongOption($argv);
  667. } else if (substr($argv[0], 0, 1) == '-' && ('-' != $argv[0] || count($argv) >1)) {
  668. $this->_parseShortOptionCluster($argv);
  669. } else if($this->_getoptConfig[self::CONFIG_PARSEALL]) {
  670. $this->_remainingArgs[] = array_shift($argv);
  671. } else {
  672. /*
  673. * We should put all other arguments in _remainingArgs and stop parsing
  674. * since CONFIG_PARSEALL is false.
  675. */
  676. $this->_remainingArgs = array_merge($this->_remainingArgs, $argv);
  677. break;
  678. }
  679. }
  680. $this->_parsed = true;
  681. return $this;
  682. }
  683. /**
  684. * Parse command-line arguments for a single long option.
  685. * A long option is preceded by a double '--' character.
  686. * Long options may not be clustered.
  687. *
  688. * @param mixed &$argv
  689. * @return void
  690. */
  691. protected function _parseLongOption(&$argv)
  692. {
  693. $optionWithParam = ltrim(array_shift($argv), '-');
  694. $l = explode('=', $optionWithParam, 2);
  695. $flag = array_shift($l);
  696. $param = array_shift($l);
  697. if (isset($param)) {
  698. array_unshift($argv, $param);
  699. }
  700. $this->_parseSingleOption($flag, $argv);
  701. }
  702. /**
  703. * Parse command-line arguments for short options.
  704. * Short options are those preceded by a single '-' character.
  705. * Short options may be clustered.
  706. *
  707. * @param mixed &$argv
  708. * @return void
  709. */
  710. protected function _parseShortOptionCluster(&$argv)
  711. {
  712. $flagCluster = ltrim(array_shift($argv), '-');
  713. foreach (str_split($flagCluster) as $flag) {
  714. $this->_parseSingleOption($flag, $argv);
  715. }
  716. }
  717. /**
  718. * Parse command-line arguments for a single option.
  719. *
  720. * @param string $flag
  721. * @param mixed $argv
  722. * @throws Zend_Console_Getopt_Exception
  723. * @return void
  724. */
  725. protected function _parseSingleOption($flag, &$argv)
  726. {
  727. if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
  728. $flag = strtolower($flag);
  729. }
  730. if (!isset($this->_ruleMap[$flag])) {
  731. require_once 'Zend/Console/Getopt/Exception.php';
  732. throw new Zend_Console_Getopt_Exception(
  733. "Option \"$flag\" is not recognized.",
  734. $this->getUsageMessage());
  735. }
  736. $realFlag = $this->_ruleMap[$flag];
  737. switch ($this->_rules[$realFlag]['param']) {
  738. case 'required':
  739. if (count($argv) > 0) {
  740. $param = array_shift($argv);
  741. $this->_checkParameterType($realFlag, $param);
  742. } else {
  743. require_once 'Zend/Console/Getopt/Exception.php';
  744. throw new Zend_Console_Getopt_Exception(
  745. "Option \"$flag\" requires a parameter.",
  746. $this->getUsageMessage());
  747. }
  748. break;
  749. case 'optional':
  750. if (count($argv) > 0 && substr($argv[0], 0, 1) != '-') {
  751. $param = array_shift($argv);
  752. $this->_checkParameterType($realFlag, $param);
  753. } else {
  754. $param = true;
  755. }
  756. break;
  757. default:
  758. $param = true;
  759. }
  760. $this->_options[$realFlag] = $param;
  761. }
  762. /**
  763. * Return true if the parameter is in a valid format for
  764. * the option $flag.
  765. * Throw an exception in most other cases.
  766. *
  767. * @param string $flag
  768. * @param string $param
  769. * @throws Zend_Console_Getopt_Exception
  770. * @return bool
  771. */
  772. protected function _checkParameterType($flag, $param)
  773. {
  774. $type = 'string';
  775. if (isset($this->_rules[$flag]['paramType'])) {
  776. $type = $this->_rules[$flag]['paramType'];
  777. }
  778. switch ($type) {
  779. case 'word':
  780. if (preg_match('/\W/', $param)) {
  781. require_once 'Zend/Console/Getopt/Exception.php';
  782. throw new Zend_Console_Getopt_Exception(
  783. "Option \"$flag\" requires a single-word parameter, but was given \"$param\".",
  784. $this->getUsageMessage());
  785. }
  786. break;
  787. case 'integer':
  788. if (preg_match('/\D/', $param)) {
  789. require_once 'Zend/Console/Getopt/Exception.php';
  790. throw new Zend_Console_Getopt_Exception(
  791. "Option \"$flag\" requires an integer parameter, but was given \"$param\".",
  792. $this->getUsageMessage());
  793. }
  794. break;
  795. case 'string':
  796. default:
  797. break;
  798. }
  799. return true;
  800. }
  801. /**
  802. * Define legal options using the gnu-style format.
  803. *
  804. * @param string $rules
  805. * @return void
  806. */
  807. protected function _addRulesModeGnu($rules)
  808. {
  809. $ruleArray = array();
  810. /**
  811. * Options may be single alphanumeric characters.
  812. * Options may have a ':' which indicates a required string parameter.
  813. * No long options or option aliases are supported in GNU style.
  814. */
  815. preg_match_all('/([a-zA-Z0-9]:?)/', $rules, $ruleArray);
  816. foreach ($ruleArray[1] as $rule) {
  817. $r = array();
  818. $flag = substr($rule, 0, 1);
  819. if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
  820. $flag = strtolower($flag);
  821. }
  822. $r['alias'][] = $flag;
  823. if (substr($rule, 1, 1) == ':') {
  824. $r['param'] = 'required';
  825. $r['paramType'] = 'string';
  826. } else {
  827. $r['param'] = 'none';
  828. }
  829. $this->_rules[$flag] = $r;
  830. $this->_ruleMap[$flag] = $flag;
  831. }
  832. }
  833. /**
  834. * Define legal options using the Zend-style format.
  835. *
  836. * @param array $rules
  837. * @throws Zend_Console_Getopt_Exception
  838. * @return void
  839. */
  840. protected function _addRulesModeZend($rules)
  841. {
  842. foreach ($rules as $ruleCode => $helpMessage)
  843. {
  844. // this may have to translate the long parm type if there
  845. // are any complaints that =string will not work (even though that use
  846. // case is not documented)
  847. if (in_array(substr($ruleCode, -2, 1), array('-', '='))) {
  848. $flagList = substr($ruleCode, 0, -2);
  849. $delimiter = substr($ruleCode, -2, 1);
  850. $paramType = substr($ruleCode, -1);
  851. } else {
  852. $flagList = $ruleCode;
  853. $delimiter = $paramType = null;
  854. }
  855. if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
  856. $flagList = strtolower($flagList);
  857. }
  858. $flags = explode('|', $flagList);
  859. $rule = array();
  860. $mainFlag = $flags[0];
  861. foreach ($flags as $flag) {
  862. if (empty($flag)) {
  863. require_once 'Zend/Console/Getopt/Exception.php';
  864. throw new Zend_Console_Getopt_Exception(
  865. "Blank flag not allowed in rule \"$ruleCode\".");
  866. }
  867. if (strlen($flag) == 1) {
  868. if (isset($this->_ruleMap[$flag])) {
  869. require_once 'Zend/Console/Getopt/Exception.php';
  870. throw new Zend_Console_Getopt_Exception(
  871. "Option \"-$flag\" is being defined more than once.");
  872. }
  873. $this->_ruleMap[$flag] = $mainFlag;
  874. $rule['alias'][] = $flag;
  875. } else {
  876. if (isset($this->_rules[$flag]) || isset($this->_ruleMap[$flag])) {
  877. require_once 'Zend/Console/Getopt/Exception.php';
  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. }