PageRenderTime 51ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/library/Zend/Console/Getopt.php

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