PageRenderTime 44ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/incubator/library/Zend/Console/Getopt.php

https://github.com/jon9872/zend-framework
PHP | 996 lines | 471 code | 51 blank | 474 comment | 73 complexity | 7ac1c374eac679d496fb02e3bd98bdf4 MD5 | raw file
  1. <?php
  2. /**
  3. * LICENSE
  4. *
  5. * This source file is subject to the new BSD license that is bundled
  6. * with this package in the file LICENSE.txt.
  7. * It is also available through the world-wide-web at this URL:
  8. * http://framework.zend.com/license/new-bsd
  9. * If you did not receive a copy of the license and are unable to
  10. * obtain it through the world-wide-web, please send an email
  11. * to license@zend.com so we can send you a copy immediately.
  12. *
  13. * @category Zend
  14. * @package Zend_Console
  15. * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
  16. * @license http://framework.zend.com/license/new-bsd New BSD License
  17. * @version $Id:$
  18. */
  19. /**
  20. * @see Zend_Console_Getopt_Exception
  21. */
  22. require_once 'Zend/Console/Getopt/Exception.php';
  23. /**
  24. * Zend_Console_Getopt is a class to parse options for command-line 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
  82. * @copyright Copyright (c) 2005-2008 Zend Technologies USA Inc. (http://www.zend.com)
  83. * @license http://framework.zend.com/license/new-bsd New BSD License
  84. * @version $Id:$
  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 Zend_Console_Getopt
  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. * @constant string
  133. */
  134. const MODE_ZEND = 'zend';
  135. /**
  136. * The options for a given application can be in multiple formats.
  137. * modeGnu is for traditional 'ab:c:' style getopt format.
  138. * modeZend is for a more structured format.
  139. *
  140. * @constant string
  141. */
  142. const MODE_GNU = 'gnu';
  143. /**
  144. * Constant tokens for various symbols used in the mode_zend
  145. * rule format.
  146. *
  147. * @constant string
  148. */
  149. const PARAM_REQUIRED = '=';
  150. /**
  151. * Constant tokens for various symbols used in the mode_zend
  152. * rule format.
  153. *
  154. * @constant string
  155. */
  156. const PARAM_OPTIONAL = '-';
  157. /**
  158. * Constant tokens for various symbols used in the mode_zend
  159. * rule format.
  160. *
  161. * @constant string
  162. */
  163. const TYPE_STRING = 's';
  164. /**
  165. * Constant tokens for various symbols used in the mode_zend
  166. * rule format.
  167. *
  168. * @constant string
  169. */
  170. const TYPE_WORD = 'w';
  171. /**
  172. * Constant tokens for various symbols used in the mode_zend
  173. * rule format.
  174. *
  175. * @constant string
  176. */
  177. const TYPE_INTEGER = 'i';
  178. /**
  179. * These are constants for optional behavior of this class.
  180. * ruleMode is either 'zend' or 'gnu' or a user-defined mode.
  181. *
  182. * @constant string
  183. */
  184. const CONFIG_RULEMODE = 'ruleMode';
  185. /**
  186. * These are constants for optional behavior of this class.
  187. * dashDash is true if '--' signifies the end of command-line options.
  188. *
  189. * @constant string
  190. */
  191. const CONFIG_DASHDASH = 'dashDash';
  192. /**
  193. * These are constants for optional behavior of this class.
  194. * ignoreCase is true if '--opt' and '--OPT' are implicitly synonyms.
  195. *
  196. * @constant string
  197. */
  198. const CONFIG_IGNORECASE = 'ignoreCase';
  199. /**
  200. * These are constants for optional behavior of this class.
  201. * parseAll is true if all options on the command line should be parsed, regardless of
  202. * whether an argument appears before them.
  203. *
  204. * @constant string
  205. */
  206. const CONFIG_PARSEALL = 'parseAll';
  207. /**
  208. * Defaults for getopt configuration are:
  209. * ruleMode is 'zend' format,
  210. * dashDash (--) token is enabled,
  211. * ignoreCase is not enabled,
  212. * parseAll is enabled.
  213. *
  214. * @var array
  215. */
  216. protected $_getoptConfig = array(
  217. self::CONFIG_RULEMODE => self::MODE_ZEND,
  218. self::CONFIG_DASHDASH => true,
  219. self::CONFIG_IGNORECASE => false,
  220. self::CONFIG_PARSEALL => true
  221. );
  222. /**
  223. * Stores the command-line arguments for the calling applicaion.
  224. *
  225. * @var array
  226. */
  227. protected $_argv = array();
  228. /**
  229. * Stores the name of the calling applicaion.
  230. *
  231. * @var string
  232. */
  233. protected $_progname = '';
  234. /**
  235. * Stores the list of legal options for this application.
  236. *
  237. * @var array
  238. */
  239. protected $_rules = array();
  240. /**
  241. * Stores alternate spellings of legal options.
  242. *
  243. * @var array
  244. */
  245. protected $_ruleMap = array();
  246. /**
  247. * Stores options given by the user in the current invocation
  248. * of the application, as well as parameters given in options.
  249. *
  250. * @var array
  251. */
  252. protected $_options = array();
  253. /**
  254. * Stores the command-line arguments other than options.
  255. *
  256. * @var array
  257. */
  258. protected $_remainingArgs = array();
  259. /**
  260. * State of the options: parsed or not yet parsed?
  261. *
  262. * @var boolean
  263. */
  264. protected $_parsed = false;
  265. /**
  266. * The constructor takes one to three parameters.
  267. *
  268. * The first parameter is $rules, which may be a string for
  269. * gnu-style format, or a structured array for Zend-style format.
  270. *
  271. * The second parameter is $argv, and it is optional. If not
  272. * specified, $argv is inferred from the global argv.
  273. *
  274. * The third parameter is an array of configuration parameters
  275. * to control the behavior of this instance of Getopt; it is optional.
  276. *
  277. * @param array $rules
  278. * @param array $argv
  279. * @param array $getoptConfig
  280. * @param string $progname
  281. * @return void
  282. */
  283. public function __construct($rules, $argv = null, $getoptConfig = array(), $progname = null)
  284. {
  285. if(isset($progname)) {
  286. $this->_progname = $progname;
  287. } else {
  288. $this->_progname = $_SERVER['argv'][0] ;
  289. }
  290. $this->setOptions($getoptConfig);
  291. $this->addRules($rules);
  292. if (!is_array($argv)) {
  293. $argv = array_slice($_SERVER['argv'], 1);
  294. }
  295. if (isset($argv)) {
  296. $this->addArguments((array)$argv);
  297. }
  298. }
  299. /**
  300. * Return the state of the option seen on the command line of the
  301. * current application invocation. This function returns true, or the
  302. * parameter to the option, if any. If the option was not given,
  303. * this function returns null.
  304. *
  305. * The magic __get method works in the context of naming the option
  306. * as a virtual member of this class.
  307. *
  308. * @param string $key
  309. * @return string
  310. */
  311. protected function __get($key)
  312. {
  313. return $this->getOption($key);
  314. }
  315. /**
  316. * Test whether a given option has been seen.
  317. *
  318. * @param string $key
  319. * @return boolean
  320. */
  321. protected function __isset($key)
  322. {
  323. $this->parse();
  324. if (isset($this->_ruleMap[$key])) {
  325. $key = $this->_ruleMap[$key];
  326. return isset($this->_options[$key]);
  327. }
  328. return false;
  329. }
  330. /**
  331. * Set the value for a given option.
  332. *
  333. * @param string $key
  334. * @param string $value
  335. * @return void
  336. */
  337. protected function __set($key, $value)
  338. {
  339. $this->parse();
  340. if (isset($this->_ruleMap[$key])) {
  341. $key = $this->_ruleMap[$key];
  342. $this->_options[$key] = $value;
  343. }
  344. }
  345. /**
  346. * Return the current set of options and parameters seen as a string.
  347. *
  348. * @return string
  349. */
  350. public function __toString()
  351. {
  352. return $this->toString();
  353. }
  354. /**
  355. * Unset an option.
  356. *
  357. * @param string $key
  358. * @return void
  359. */
  360. public function __unset($key)
  361. {
  362. $this->parse();
  363. if (isset($this->_ruleMap[$key])) {
  364. $key = $this->_ruleMap[$key];
  365. unset($this->_options[$key]);
  366. }
  367. }
  368. /**
  369. * Define additional command-line arguments.
  370. * These are appended to those defined when the constructor was called.
  371. *
  372. * @param array $argv
  373. * @return Zend_Console_Getopt
  374. */
  375. public function addArguments($argv)
  376. {
  377. $this->_argv = array_merge($this->_argv, $argv);
  378. $this->_parsed = false;
  379. return $this;
  380. }
  381. /**
  382. * Define full set of command-line arguments.
  383. * These replace any currently defined.
  384. *
  385. * @param array $argv
  386. * @return Zend_Console_Getopt
  387. */
  388. public function setArguments($argv)
  389. {
  390. $this->_argv = $argv;
  391. $this->_parsed = false;
  392. return $this;
  393. }
  394. /**
  395. * Define multiple configuration options from an associative array.
  396. * These are not program options, but properties to configure
  397. * the behavior of Zend_Console_Getopt.
  398. *
  399. * @param array $getoptConfig
  400. * @return Zend_Console_Getopt
  401. */
  402. public function setOptions($getoptConfig)
  403. {
  404. if (isset($getoptConfig)) {
  405. foreach ($getoptConfig as $key => $value) {
  406. $this->setOption($key, $value);
  407. }
  408. }
  409. return $this;
  410. }
  411. /**
  412. * Define one configuration option as a key/value pair.
  413. * These are not program options, but properties to configure
  414. * the behavior of Zend_Console_Getopt.
  415. *
  416. * @param string $configKey
  417. * @param string $configValue
  418. * @return Zend_Console_Getopt
  419. */
  420. public function setOption($configKey, $configValue)
  421. {
  422. if ($configKey !== null) {
  423. $this->_getoptConfig[$configKey] = $configValue;
  424. }
  425. return $this;
  426. }
  427. /**
  428. * Define additional option rules.
  429. * These are appended to the rules defined when the constructor was called.
  430. *
  431. * @param array $rules
  432. * @return Zend_Console_Getopt
  433. */
  434. public function addRules($rules)
  435. {
  436. $ruleMode = $this->_getoptConfig['ruleMode'];
  437. switch ($this->_getoptConfig['ruleMode']) {
  438. case self::MODE_ZEND:
  439. if (is_array($rules)) {
  440. $this->_addRulesModeZend($rules);
  441. break;
  442. }
  443. $this->_getoptConfig['ruleMode'] = self::MODE_GNU;
  444. // intentional fallthrough
  445. case self::MODE_GNU:
  446. $this->_addRulesModeGnu($rules);
  447. break;
  448. default:
  449. /**
  450. * Call addRulesModeFoo() for ruleMode 'foo'.
  451. * The developer should subclass Getopt and
  452. * provide this method.
  453. */
  454. $method = '_addRulesMode' . ucfirst($ruleMode);
  455. $this->$method($rules);
  456. }
  457. $this->_parsed = false;
  458. return $this;
  459. }
  460. /**
  461. * Return the current set of options and parameters seen as a string.
  462. *
  463. * @return string
  464. */
  465. public function toString()
  466. {
  467. $this->parse();
  468. $s = array();
  469. foreach ($this->_options as $flag => $value) {
  470. $s[] = $flag . '=' . ($value === true ? 'true' : $value);
  471. }
  472. return implode(' ', $s);
  473. }
  474. /**
  475. * Return the current set of options and parameters seen
  476. * as an array of canonical options and parameters.
  477. *
  478. * Clusters have been expanded, and option aliases
  479. * have been mapped to their primary option names.
  480. *
  481. * @return array
  482. */
  483. public function toArray()
  484. {
  485. $this->parse();
  486. $s = array();
  487. foreach ($this->_options as $flag => $value) {
  488. $s[] = $flag;
  489. if ($value !== true) {
  490. $s[] = $value;
  491. }
  492. }
  493. return $s;
  494. }
  495. /**
  496. * Return the current set of options and parameters seen in Json format.
  497. *
  498. * @return string
  499. */
  500. public function toJson()
  501. {
  502. $this->parse();
  503. $j = array();
  504. foreach ($this->_options as $flag => $value) {
  505. $j['options'][] = array(
  506. 'option' => array(
  507. 'flag' => $flag,
  508. 'parameter' => $value
  509. )
  510. );
  511. }
  512. /**
  513. * @see Zend_Json
  514. */
  515. require_once 'Zend/Json.php';
  516. $json = Zend_Json::encode($j);
  517. return $json;
  518. }
  519. /**
  520. * Return the current set of options and parameters seen in XML format.
  521. *
  522. * @return string
  523. */
  524. public function toXml()
  525. {
  526. $this->parse();
  527. $doc = new DomDocument('1.0', 'utf-8');
  528. $optionsNode = $doc->createElement('options');
  529. $doc->appendChild($optionsNode);
  530. foreach ($this->_options as $flag => $value) {
  531. $optionNode = $doc->createElement('option');
  532. $optionNode->setAttribute('flag', utf8_encode($flag));
  533. if ($value !== true) {
  534. $optionNode->setAttribute('parameter', utf8_encode($value));
  535. }
  536. $optionsNode->appendChild($optionNode);
  537. }
  538. $xml = $doc->saveXML();
  539. return $xml;
  540. }
  541. /**
  542. * Return a list of options that have been seen in the current argv.
  543. *
  544. * @return array
  545. */
  546. public function getOptions()
  547. {
  548. $this->parse();
  549. return array_keys($this->_options);
  550. }
  551. /**
  552. * Return the state of the option seen on the command line of the
  553. * current application invocation.
  554. *
  555. * This function returns true, or the parameter value to the option, if any.
  556. * If the option was not given, this function returns false.
  557. *
  558. * @param string $flag
  559. * @return mixed|null
  560. */
  561. public function getOption($flag)
  562. {
  563. $this->parse();
  564. if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
  565. $flag = strtolower($flag);
  566. }
  567. if (isset($this->_ruleMap[$flag])) {
  568. $flag = $this->_ruleMap[$flag];
  569. if (isset($this->_options[$flag])) {
  570. return $this->_options[$flag];
  571. }
  572. }
  573. return null;
  574. }
  575. /**
  576. * Return the arguments from the command-line following all options found.
  577. *
  578. * @return array
  579. */
  580. public function getRemainingArgs()
  581. {
  582. $this->parse();
  583. return $this->_remainingArgs;
  584. }
  585. /**
  586. * Return a useful option reference, formatted for display in an
  587. * error message.
  588. *
  589. * Note that this usage information is provided in most Exceptions
  590. * generated by this class.
  591. *
  592. * @return string
  593. */
  594. public function getUsageMessage()
  595. {
  596. $usage = "Usage: {$this->_progname} [ options ]\n";
  597. $maxLen = 20;
  598. foreach ($this->_rules as $rule) {
  599. $flags = array();
  600. if (is_array($rule['alias'])) {
  601. foreach ($rule['alias'] as $flag) {
  602. $flags[] = (strlen($flag) == 1 ? '-' : '--') . $flag;
  603. }
  604. }
  605. $linepart['name'] = implode('|', $flags);
  606. if (isset($rule['param']) && $rule['param'] != 'none') {
  607. $linepart['name'] .= ' ';
  608. switch ($rule['param']) {
  609. case 'optional':
  610. $linepart['name'] .= "[ <{$rule['paramType']}> ]";
  611. break;
  612. case 'required':
  613. $linepart['name'] .= "<{$rule['paramType']}>";
  614. break;
  615. }
  616. }
  617. if (strlen($linepart['name']) > $maxLen) {
  618. $maxLen = strlen($linepart['name']);
  619. }
  620. $linepart['help'] = '';
  621. if (isset($rule['help'])) {
  622. $linepart['help'] .= $rule['help'];
  623. }
  624. $lines[] = $linepart;
  625. }
  626. foreach ($lines as $linepart) {
  627. $usage .= sprintf("%s %s\n",
  628. str_pad($linepart['name'], $maxLen),
  629. $linepart['help']);
  630. }
  631. return $usage;
  632. }
  633. /**
  634. * Define aliases for options.
  635. *
  636. * The parameter $aliasMap is an associative array
  637. * mapping option name (short or long) to an alias.
  638. *
  639. * @param array $aliasMap
  640. * @throws Zend_Console_Getopt_Exception
  641. * @return Zend_Console_Getopt
  642. */
  643. public function setAliases($aliasMap)
  644. {
  645. foreach ($aliasMap as $flag => $alias)
  646. {
  647. if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
  648. $flag = strtolower($flag);
  649. $alias = strtolower($alias);
  650. }
  651. if (!isset($this->_ruleMap[$flag])) {
  652. continue;
  653. }
  654. $flag = $this->_ruleMap[$flag];
  655. if (isset($this->_rules[$alias]) || isset($this->_ruleMap[$alias])) {
  656. $o = (strlen($alias) == 1 ? '-' : '--') . $alias;
  657. throw new Zend_Console_Getopt_Exception(
  658. "Option \"$o\" is being defined more than once.");
  659. }
  660. $this->_rules[$flag]['alias'][] = $alias;
  661. $this->_ruleMap[$alias] = $flag;
  662. }
  663. return $this;
  664. }
  665. /**
  666. * Define help messages for options.
  667. *
  668. * The parameter $help_map is an associative array
  669. * mapping option name (short or long) to the help string.
  670. *
  671. * @param array $helpMap
  672. * @return Zend_Console_Getopt
  673. */
  674. public function setHelp($helpMap)
  675. {
  676. foreach ($helpMap as $flag => $help)
  677. {
  678. if (!isset($this->_ruleMap[$flag])) {
  679. continue;
  680. }
  681. $flag = $this->_ruleMap[$flag];
  682. $this->_rules[$flag]['help'] = $help;
  683. }
  684. return $this;
  685. }
  686. /**
  687. * Parse command-line arguments and find both long and short
  688. * options.
  689. *
  690. * Also find option parameters, and remaining arguments after
  691. * all options have been parsed.
  692. *
  693. * @return Zend_Console_Getopt|null
  694. */
  695. public function parse()
  696. {
  697. if ($this->_parsed === true) {
  698. return;
  699. }
  700. $argv = $this->_argv;
  701. $this->_options = array();
  702. $this->_remainingArgs = array();
  703. while (count($argv) > 0) {
  704. if ($argv[0] == '--') {
  705. array_shift($argv);
  706. if ($this->_getoptConfig[self::CONFIG_DASHDASH]) {
  707. $this->_remainingArgs = array_merge($this->_remainingArgs, $argv);
  708. break;
  709. }
  710. }
  711. if (substr($argv[0], 0, 2) == '--') {
  712. $this->_parseLongOption($argv);
  713. } else if (substr($argv[0], 0, 1) == '-') {
  714. $this->_parseShortOptionCluster($argv);
  715. } else if($this->_getoptConfig[self::CONFIG_PARSEALL]) {
  716. $this->_remainingArgs[] = array_shift($argv);
  717. } else {
  718. /*
  719. * We should put all other arguments in _remainingArgs and stop parsing
  720. * since CONFIG_PARSEALL is false.
  721. */
  722. $this->_remainingArgs[] = $argv;
  723. break;
  724. }
  725. }
  726. $this->_parsed = true;
  727. return $this;
  728. }
  729. /**
  730. * Parse command-line arguments for a single long option.
  731. * A long option is preceded by a double '--' character.
  732. * Long options may not be clustered.
  733. *
  734. * @param array &$argv
  735. * @return void
  736. */
  737. protected function _parseLongOption(&$argv)
  738. {
  739. $optionWithParam = ltrim(array_shift($argv), '-');
  740. $l = explode('=', $optionWithParam);
  741. $flag = array_shift($l);
  742. $param = array_shift($l);
  743. if (isset($param)) {
  744. array_unshift($argv, $param);
  745. }
  746. $this->_parseSingleOption($flag, $argv);
  747. }
  748. /**
  749. * Parse command-line arguments for short options.
  750. * Short options are those preceded by a single '-' character.
  751. * Short options may be clustered.
  752. *
  753. * @param array &$argv
  754. * @return void
  755. */
  756. protected function _parseShortOptionCluster(&$argv)
  757. {
  758. $flagCluster = ltrim(array_shift($argv), '-');
  759. foreach (str_split($flagCluster) as $flag) {
  760. $this->_parseSingleOption($flag, $argv);
  761. }
  762. }
  763. /**
  764. * Parse command-line arguments for a single option.
  765. *
  766. * @param string $flag
  767. * @param array $argv
  768. * @throws Zend_Console_Getopt_Exception
  769. * @return void
  770. */
  771. protected function _parseSingleOption($flag, &$argv)
  772. {
  773. if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
  774. $flag = strtolower($flag);
  775. }
  776. if (!isset($this->_ruleMap[$flag])) {
  777. throw new Zend_Console_Getopt_Exception(
  778. "Option \"$flag\" is not recognized.",
  779. $this->getUsageMessage());
  780. }
  781. $realFlag = $this->_ruleMap[$flag];
  782. switch ($this->_rules[$realFlag]['param']) {
  783. case 'required':
  784. if (count($argv) > 0) {
  785. $param = array_shift($argv);
  786. $this->_checkParameterType($realFlag, $param);
  787. } else {
  788. throw new Zend_Console_Getopt_Exception(
  789. "Option \"$flag\" requires a parameter.",
  790. $this->getUsageMessage());
  791. }
  792. break;
  793. case 'optional':
  794. if (count($argv) > 0 && substr($argv[0], 0, 1) != '-') {
  795. $param = array_shift($argv);
  796. $this->_checkParameterType($realFlag, $param);
  797. } else {
  798. $param = true;
  799. }
  800. break;
  801. default:
  802. $param = true;
  803. }
  804. $this->_options[$realFlag] = $param;
  805. }
  806. /**
  807. * Return true if the parameter is in a valid format for
  808. * the option $flag.
  809. * Throw an exception in most other cases.
  810. *
  811. * @param string $flag
  812. * @param string $param
  813. * @throws Zend_Console_Getopt_Exception
  814. * @return boolean
  815. */
  816. protected function _checkParameterType($flag, $param)
  817. {
  818. $type = 'string';
  819. if (isset($this->_rules[$flag]['paramType'])) {
  820. $type = $this->_rules[$flag]['paramType'];
  821. }
  822. switch ($type) {
  823. case 'word':
  824. if (preg_match('/\W/', $param)) {
  825. throw new Zend_Console_Getopt_Exception(
  826. "Option \"$flag\" requires a single-word parameter, but was given \"$param\".",
  827. $this->getUsageMessage());
  828. }
  829. break;
  830. case 'integer':
  831. if (preg_match('/\D/', $param)) {
  832. throw new Zend_Console_Getopt_Exception(
  833. "Option \"$flag\" requires an integer parameter, but was given \"$param\".",
  834. $this->getUsageMessage());
  835. }
  836. break;
  837. case 'string':
  838. default:
  839. break;
  840. }
  841. return true;
  842. }
  843. /**
  844. * Define legal options using the gnu-style format.
  845. *
  846. * @param string $rules
  847. * @return void
  848. */
  849. protected function _addRulesModeGnu($rules)
  850. {
  851. $ruleArray = array();
  852. /**
  853. * Options may be single alphanumeric characters.
  854. * Options may have a ':' which indicates a required string parameter.
  855. * No long options or option aliases are supported in GNU style.
  856. */
  857. preg_match_all('/([a-zA-Z0-9]:?)/', $rules, $ruleArray);
  858. foreach ($ruleArray[1] as $rule) {
  859. $r = array();
  860. $flag = substr($rule, 0, 1);
  861. if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
  862. $flag = strtolower($flag);
  863. }
  864. $r['alias'][] = $flag;
  865. if (substr($rule, 1, 1) == ':') {
  866. $r['param'] = 'required';
  867. $r['paramType'] = 'string';
  868. } else {
  869. $r['param'] = 'none';
  870. }
  871. $this->_rules[$flag] = $r;
  872. $this->_ruleMap[$flag] = $flag;
  873. }
  874. }
  875. /**
  876. * Define legal options using the Zend-style format.
  877. *
  878. * @param array $rules
  879. * @throws Zend_Console_Getopt_Exception
  880. * @return void
  881. */
  882. protected function _addRulesModeZend($rules)
  883. {
  884. foreach ($rules as $ruleCode => $helpMessage)
  885. {
  886. $tokens = preg_split('/([=-])/',
  887. $ruleCode, 2, PREG_SPLIT_DELIM_CAPTURE);
  888. $flagList = array_shift($tokens);
  889. $delimiter = array_shift($tokens);
  890. $paramType = array_shift($tokens);
  891. if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
  892. $flagList = strtolower($flagList);
  893. }
  894. $flags = explode('|', $flagList);
  895. $rule = array();
  896. $mainFlag = $flags[0];
  897. foreach ($flags as $flag) {
  898. if (empty($flag)) {
  899. throw new Zend_Console_Getopt_Exception(
  900. "Blank flag not allowed in rule \"$ruleCode\".");
  901. }
  902. if (strlen($flag) == 1) {
  903. if (isset($this->_ruleMap[$flag])) {
  904. throw new Zend_Console_Getopt_Exception(
  905. "Option \"-$flag\" is being defined more than once.");
  906. }
  907. $this->_ruleMap[$flag] = $mainFlag;
  908. $rule['alias'][] = $flag;
  909. } else {
  910. if (isset($this->_rules[$flag]) || isset($this->_ruleMap[$flag])) {
  911. throw new Zend_Console_Getopt_Exception(
  912. "Option \"--$flag\" is being defined more than once.");
  913. }
  914. $this->_ruleMap[$flag] = $mainFlag;
  915. $rule['alias'][] = $flag;
  916. }
  917. }
  918. if (isset($delimiter)) {
  919. switch ($delimiter) {
  920. case self::PARAM_REQUIRED:
  921. $rule['param'] = 'required';
  922. break;
  923. case self::PARAM_OPTIONAL:
  924. default:
  925. $rule['param'] = 'optional';
  926. }
  927. switch (substr($paramType, 0, 1)) {
  928. case self::TYPE_WORD:
  929. $rule['paramType'] = 'word';
  930. break;
  931. case self::TYPE_INTEGER:
  932. $rule['paramType'] = 'integer';
  933. break;
  934. case self::TYPE_STRING:
  935. default:
  936. $rule['paramType'] = 'string';
  937. }
  938. } else {
  939. $rule['param'] = 'none';
  940. }
  941. $rule['help'] = $helpMessage;
  942. $this->_rules[$mainFlag] = $rule;
  943. }
  944. }
  945. }