PageRenderTime 62ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/library/Zend/Console/Getopt.php

https://bitbucket.org/baruffaldi/website-2008-computer-shopping-3
PHP | 949 lines | 462 code | 44 blank | 443 comment | 69 complexity | 091b8db0d54b8a4ad5ecde7452b0a033 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. $this->_getoptConfig['ruleMode'] = self::MODE_GNU;
  387. // intentional fallthrough
  388. case self::MODE_GNU:
  389. $this->_addRulesModeGnu($rules);
  390. break;
  391. default:
  392. /**
  393. * Call addRulesModeFoo() for ruleMode 'foo'.
  394. * The developer should subclass Getopt and
  395. * provide this method.
  396. */
  397. $method = '_addRulesMode' . ucfirst($ruleMode);
  398. $this->$method($rules);
  399. }
  400. $this->_parsed = false;
  401. return $this;
  402. }
  403. /**
  404. * Return the current set of options and parameters seen as a string.
  405. *
  406. * @return string
  407. */
  408. public function toString()
  409. {
  410. $this->parse();
  411. $s = array();
  412. foreach ($this->_options as $flag => $value) {
  413. $s[] = $flag . '=' . ($value === true ? 'true' : $value);
  414. }
  415. return implode(' ', $s);
  416. }
  417. /**
  418. * Return the current set of options and parameters seen
  419. * as an array of canonical options and parameters.
  420. *
  421. * Clusters have been expanded, and option aliases
  422. * have been mapped to their primary option names.
  423. *
  424. * @return array
  425. */
  426. public function toArray()
  427. {
  428. $this->parse();
  429. $s = array();
  430. foreach ($this->_options as $flag => $value) {
  431. $s[] = $flag;
  432. if ($value !== true) {
  433. $s[] = $value;
  434. }
  435. }
  436. return $s;
  437. }
  438. /**
  439. * Return the current set of options and parameters seen in Json format.
  440. *
  441. * @return string
  442. */
  443. public function toJson()
  444. {
  445. $this->parse();
  446. $j = array();
  447. foreach ($this->_options as $flag => $value) {
  448. $j['options'][] = array(
  449. 'option' => array(
  450. 'flag' => $flag,
  451. 'parameter' => $value
  452. )
  453. );
  454. }
  455. /**
  456. * @see Zend_Json
  457. */
  458. require_once 'Zend/Json.php';
  459. $json = Zend_Json::encode($j);
  460. return $json;
  461. }
  462. /**
  463. * Return the current set of options and parameters seen in XML format.
  464. *
  465. * @return string
  466. */
  467. public function toXml()
  468. {
  469. $this->parse();
  470. $doc = new DomDocument('1.0', 'utf-8');
  471. $optionsNode = $doc->createElement('options');
  472. $doc->appendChild($optionsNode);
  473. foreach ($this->_options as $flag => $value) {
  474. $optionNode = $doc->createElement('option');
  475. $optionNode->setAttribute('flag', utf8_encode($flag));
  476. if ($value !== true) {
  477. $optionNode->setAttribute('parameter', utf8_encode($value));
  478. }
  479. $optionsNode->appendChild($optionNode);
  480. }
  481. $xml = $doc->saveXML();
  482. return $xml;
  483. }
  484. /**
  485. * Return a list of options that have been seen in the current argv.
  486. *
  487. * @return array
  488. */
  489. public function getOptions()
  490. {
  491. $this->parse();
  492. return array_keys($this->_options);
  493. }
  494. /**
  495. * Return the state of the option seen on the command line of the
  496. * current application invocation.
  497. *
  498. * This function returns true, or the parameter value to the option, if any.
  499. * If the option was not given, this function returns false.
  500. *
  501. * @param string $flag
  502. * @return mixed
  503. */
  504. public function getOption($flag)
  505. {
  506. $this->parse();
  507. if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
  508. $flag = strtolower($flag);
  509. }
  510. if (isset($this->_ruleMap[$flag])) {
  511. $flag = $this->_ruleMap[$flag];
  512. if (isset($this->_options[$flag])) {
  513. return $this->_options[$flag];
  514. }
  515. }
  516. return null;
  517. }
  518. /**
  519. * Return the arguments from the command-line following all options found.
  520. *
  521. * @return array
  522. */
  523. public function getRemainingArgs()
  524. {
  525. $this->parse();
  526. return $this->_remainingArgs;
  527. }
  528. /**
  529. * Return a useful option reference, formatted for display in an
  530. * error message.
  531. *
  532. * Note that this usage information is provided in most Exceptions
  533. * generated by this class.
  534. *
  535. * @return string
  536. */
  537. public function getUsageMessage()
  538. {
  539. $usage = "Usage: {$this->_progname} [ options ]\n";
  540. $maxLen = 20;
  541. foreach ($this->_rules as $rule) {
  542. $flags = array();
  543. if (is_array($rule['alias'])) {
  544. foreach ($rule['alias'] as $flag) {
  545. $flags[] = (strlen($flag) == 1 ? '-' : '--') . $flag;
  546. }
  547. }
  548. $linepart['name'] = implode('|', $flags);
  549. if (isset($rule['param']) && $rule['param'] != 'none') {
  550. $linepart['name'] .= ' ';
  551. switch ($rule['param']) {
  552. case 'optional':
  553. $linepart['name'] .= "[ <{$rule['paramType']}> ]";
  554. break;
  555. case 'required':
  556. $linepart['name'] .= "<{$rule['paramType']}>";
  557. break;
  558. }
  559. }
  560. if (strlen($linepart['name']) > $maxLen) {
  561. $maxLen = strlen($linepart['name']);
  562. }
  563. $linepart['help'] = '';
  564. if (isset($rule['help'])) {
  565. $linepart['help'] .= $rule['help'];
  566. }
  567. $lines[] = $linepart;
  568. }
  569. foreach ($lines as $linepart) {
  570. $usage .= sprintf("%s %s\n",
  571. str_pad($linepart['name'], $maxLen),
  572. $linepart['help']);
  573. }
  574. return $usage;
  575. }
  576. /**
  577. * Define aliases for options.
  578. *
  579. * The parameter $aliasMap is an associative array
  580. * mapping option name (short or long) to an alias.
  581. *
  582. * @param array $aliasMap
  583. * @throws Zend_Console_Getopt_Exception
  584. * @return Zend_Console_Getopt Provides a fluent interface
  585. */
  586. public function setAliases($aliasMap)
  587. {
  588. foreach ($aliasMap as $flag => $alias)
  589. {
  590. if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
  591. $flag = strtolower($flag);
  592. $alias = strtolower($alias);
  593. }
  594. if (!isset($this->_ruleMap[$flag])) {
  595. continue;
  596. }
  597. $flag = $this->_ruleMap[$flag];
  598. if (isset($this->_rules[$alias]) || isset($this->_ruleMap[$alias])) {
  599. $o = (strlen($alias) == 1 ? '-' : '--') . $alias;
  600. /**
  601. * @see Zend_Console_Getopt_Exception
  602. */
  603. throw new Zend_Console_Getopt_Exception(
  604. "Option \"$o\" is being defined more than once.");
  605. }
  606. $this->_rules[$flag]['alias'][] = $alias;
  607. $this->_ruleMap[$alias] = $flag;
  608. }
  609. return $this;
  610. }
  611. /**
  612. * Define help messages for options.
  613. *
  614. * The parameter $help_map is an associative array
  615. * mapping option name (short or long) to the help string.
  616. *
  617. * @param array $helpMap
  618. * @return Zend_Console_Getopt Provides a fluent interface
  619. */
  620. public function setHelp($helpMap)
  621. {
  622. foreach ($helpMap as $flag => $help)
  623. {
  624. if (!isset($this->_ruleMap[$flag])) {
  625. continue;
  626. }
  627. $flag = $this->_ruleMap[$flag];
  628. $this->_rules[$flag]['help'] = $help;
  629. }
  630. return $this;
  631. }
  632. /**
  633. * Parse command-line arguments and find both long and short
  634. * options.
  635. *
  636. * Also find option parameters, and remaining arguments after
  637. * all options have been parsed.
  638. *
  639. * @return Zend_Console_Getopt|null Provides a fluent interface
  640. */
  641. public function parse()
  642. {
  643. if ($this->_parsed === true) {
  644. return;
  645. }
  646. $argv = $this->_argv;
  647. $this->_options = array();
  648. $this->_remainingArgs = array();
  649. while (count($argv) > 0) {
  650. if ($argv[0] == '--') {
  651. array_shift($argv);
  652. if ($this->_getoptConfig[self::CONFIG_DASHDASH]) {
  653. $this->_remainingArgs = array_merge($this->_remainingArgs, $argv);
  654. break;
  655. }
  656. }
  657. if (substr($argv[0], 0, 2) == '--') {
  658. $this->_parseLongOption($argv);
  659. } else if (substr($argv[0], 0, 1) == '-') {
  660. $this->_parseShortOptionCluster($argv);
  661. } else {
  662. $this->_remainingArgs[] = array_shift($argv);
  663. }
  664. }
  665. $this->_parsed = true;
  666. return $this;
  667. }
  668. /**
  669. * Parse command-line arguments for a single long option.
  670. * A long option is preceded by a double '--' character.
  671. * Long options may not be clustered.
  672. *
  673. * @param mixed &$argv
  674. * @return void
  675. */
  676. protected function _parseLongOption(&$argv)
  677. {
  678. $optionWithParam = ltrim(array_shift($argv), '-');
  679. $l = explode('=', $optionWithParam);
  680. $flag = array_shift($l);
  681. $param = array_shift($l);
  682. if (isset($param)) {
  683. array_unshift($argv, $param);
  684. }
  685. $this->_parseSingleOption($flag, $argv);
  686. }
  687. /**
  688. * Parse command-line arguments for short options.
  689. * Short options are those preceded by a single '-' character.
  690. * Short options may be clustered.
  691. *
  692. * @param mixed &$argv
  693. * @return void
  694. */
  695. protected function _parseShortOptionCluster(&$argv)
  696. {
  697. $flagCluster = ltrim(array_shift($argv), '-');
  698. foreach (str_split($flagCluster) as $flag) {
  699. $this->_parseSingleOption($flag, $argv);
  700. }
  701. }
  702. /**
  703. * Parse command-line arguments for a single option.
  704. *
  705. * @param string $flag
  706. * @param mixed $argv
  707. * @throws Zend_Console_Getopt_Exception
  708. * @return void
  709. */
  710. protected function _parseSingleOption($flag, &$argv)
  711. {
  712. if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
  713. $flag = strtolower($flag);
  714. }
  715. if (!isset($this->_ruleMap[$flag])) {
  716. /**
  717. * @see Zend_Console_Getopt_Exception
  718. */
  719. throw new Zend_Console_Getopt_Exception(
  720. "Option \"$flag\" is not recognized.",
  721. $this->getUsageMessage());
  722. }
  723. $realFlag = $this->_ruleMap[$flag];
  724. switch ($this->_rules[$realFlag]['param']) {
  725. case 'required':
  726. if (count($argv) > 0) {
  727. $param = array_shift($argv);
  728. $this->_checkParameterType($realFlag, $param);
  729. } else {
  730. /**
  731. * @see Zend_Console_Getopt_Exception
  732. */
  733. throw new Zend_Console_Getopt_Exception(
  734. "Option \"$flag\" requires a parameter.",
  735. $this->getUsageMessage());
  736. }
  737. break;
  738. case 'optional':
  739. if (count($argv) > 0 && substr($argv[0], 0, 1) != '-') {
  740. $param = array_shift($argv);
  741. $this->_checkParameterType($realFlag, $param);
  742. } else {
  743. $param = true;
  744. }
  745. break;
  746. default:
  747. $param = true;
  748. }
  749. $this->_options[$realFlag] = $param;
  750. }
  751. /**
  752. * Return true if the parameter is in a valid format for
  753. * the option $flag.
  754. * Throw an exception in most other cases.
  755. *
  756. * @param string $flag
  757. * @param string $param
  758. * @throws Zend_Console_Getopt_Exception
  759. * @return bool
  760. */
  761. protected function _checkParameterType($flag, $param)
  762. {
  763. $type = 'string';
  764. if (isset($this->_rules[$flag]['paramType'])) {
  765. $type = $this->_rules[$flag]['paramType'];
  766. }
  767. switch ($type) {
  768. case 'word':
  769. if (preg_match('/\W/', $param)) {
  770. /**
  771. * @see Zend_Console_Getopt_Exception
  772. */
  773. throw new Zend_Console_Getopt_Exception(
  774. "Option \"$flag\" requires a single-word parameter, but was given \"$param\".",
  775. $this->getUsageMessage());
  776. }
  777. break;
  778. case 'integer':
  779. if (preg_match('/\D/', $param)) {
  780. /**
  781. * @see Zend_Console_Getopt_Exception
  782. */
  783. throw new Zend_Console_Getopt_Exception(
  784. "Option \"$flag\" requires an integer parameter, but was given \"$param\".",
  785. $this->getUsageMessage());
  786. }
  787. break;
  788. case 'string':
  789. default:
  790. break;
  791. }
  792. return true;
  793. }
  794. /**
  795. * Define legal options using the gnu-style format.
  796. *
  797. * @param string $rules
  798. * @return void
  799. */
  800. protected function _addRulesModeGnu($rules)
  801. {
  802. $ruleArray = array();
  803. /**
  804. * Options may be single alphanumeric characters.
  805. * Options may have a ':' which indicates a required string parameter.
  806. * No long options or option aliases are supported in GNU style.
  807. */
  808. preg_match_all('/([a-zA-Z0-9]:?)/', $rules, $ruleArray);
  809. foreach ($ruleArray[1] as $rule) {
  810. $r = array();
  811. $flag = substr($rule, 0, 1);
  812. if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
  813. $flag = strtolower($flag);
  814. }
  815. $r['alias'][] = $flag;
  816. if (substr($rule, 1, 1) == ':') {
  817. $r['param'] = 'required';
  818. $r['paramType'] = 'string';
  819. } else {
  820. $r['param'] = 'none';
  821. }
  822. $this->_rules[$flag] = $r;
  823. $this->_ruleMap[$flag] = $flag;
  824. }
  825. }
  826. /**
  827. * Define legal options using the Zend-style format.
  828. *
  829. * @param array $rules
  830. * @throws Zend_Console_Getopt_Exception
  831. * @return void
  832. */
  833. protected function _addRulesModeZend($rules)
  834. {
  835. foreach ($rules as $ruleCode => $helpMessage)
  836. {
  837. $tokens = preg_split('/([=-])/',
  838. $ruleCode, 2, PREG_SPLIT_DELIM_CAPTURE);
  839. $flagList = array_shift($tokens);
  840. $delimiter = array_shift($tokens);
  841. $paramType = array_shift($tokens);
  842. if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
  843. $flagList = strtolower($flagList);
  844. }
  845. $flags = explode('|', $flagList);
  846. $rule = array();
  847. $mainFlag = $flags[0];
  848. foreach ($flags as $flag) {
  849. if (empty($flag)) {
  850. /**
  851. * @see Zend_Console_Getopt_Exception
  852. */
  853. throw new Zend_Console_Getopt_Exception(
  854. "Blank flag not allowed in rule \"$ruleCode\".");
  855. }
  856. if (strlen($flag) == 1) {
  857. if (isset($this->_ruleMap[$flag])) {
  858. /**
  859. * @see Zend_Console_Getopt_Exception
  860. */
  861. throw new Zend_Console_Getopt_Exception(
  862. "Option \"-$flag\" is being defined more than once.");
  863. }
  864. $this->_ruleMap[$flag] = $mainFlag;
  865. $rule['alias'][] = $flag;
  866. } else {
  867. if (isset($this->_rules[$flag]) || isset($this->_ruleMap[$flag])) {
  868. /**
  869. * @see Zend_Console_Getopt_Exception
  870. */
  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. }
  877. }
  878. if (isset($delimiter)) {
  879. switch ($delimiter) {
  880. case self::PARAM_REQUIRED:
  881. $rule['param'] = 'required';
  882. break;
  883. case self::PARAM_OPTIONAL:
  884. default:
  885. $rule['param'] = 'optional';
  886. }
  887. switch (substr($paramType, 0, 1)) {
  888. case self::TYPE_WORD:
  889. $rule['paramType'] = 'word';
  890. break;
  891. case self::TYPE_INTEGER:
  892. $rule['paramType'] = 'integer';
  893. break;
  894. case self::TYPE_STRING:
  895. default:
  896. $rule['paramType'] = 'string';
  897. }
  898. } else {
  899. $rule['param'] = 'none';
  900. }
  901. $rule['help'] = $helpMessage;
  902. $this->_rules[$mainFlag] = $rule;
  903. }
  904. }
  905. }