PageRenderTime 53ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/cakesocial.local/app/vendors/zend/laboratory/Zend_Tool/library/ZendL/Console/Getopt.php

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