PageRenderTime 55ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/library/Zend/Console/Getopt.php

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