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

/library/System/Independent/Shell/class.Getopt.php

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