PageRenderTime 105ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/Zend/Console/Getopt.php

https://bitbucket.org/simukti/zf1
PHP | 970 lines | 499 code | 45 blank | 426 comment | 82 complexity | 2e5e2531b48895a1891999af4c07b4d7 MD5 | raw file
  1. <?php
  2. /**
  3. * Zend_Console_Getopt is a class to parse options for command-line
  4. * applications.
  5. *
  6. * LICENSE
  7. *
  8. * This source file is subject to the new BSD license that is bundled
  9. * with this package in the file LICENSE.txt.
  10. * It is also available through the world-wide-web at this URL:
  11. * http://framework.zend.com/license/new-bsd
  12. * If you did not receive a copy of the license and are unable to
  13. * obtain it through the world-wide-web, please send an email
  14. * to license@zend.com so we can send you a copy immediately.
  15. *
  16. * @category Zend
  17. * @package Zend_Console_Getopt
  18. * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id: Getopt.php 24593 2012-01-05 20:35:02Z matthew $
  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-2012 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. require_once '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. require_once '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. require_once '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. require_once '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. $lines = array();
  564. foreach ($this->_rules as $rule) {
  565. $flags = array();
  566. if (is_array($rule['alias'])) {
  567. foreach ($rule['alias'] as $flag) {
  568. $flags[] = (strlen($flag) == 1 ? '-' : '--') . $flag;
  569. }
  570. }
  571. $linepart['name'] = implode('|', $flags);
  572. if (isset($rule['param']) && $rule['param'] != 'none') {
  573. $linepart['name'] .= ' ';
  574. switch ($rule['param']) {
  575. case 'optional':
  576. $linepart['name'] .= "[ <{$rule['paramType']}> ]";
  577. break;
  578. case 'required':
  579. $linepart['name'] .= "<{$rule['paramType']}>";
  580. break;
  581. }
  582. }
  583. if (strlen($linepart['name']) > $maxLen) {
  584. $maxLen = strlen($linepart['name']);
  585. }
  586. $linepart['help'] = '';
  587. if (isset($rule['help'])) {
  588. $linepart['help'] .= $rule['help'];
  589. }
  590. $lines[] = $linepart;
  591. }
  592. foreach ($lines as $linepart) {
  593. $usage .= sprintf("%s %s\n",
  594. str_pad($linepart['name'], $maxLen),
  595. $linepart['help']);
  596. }
  597. return $usage;
  598. }
  599. /**
  600. * Define aliases for options.
  601. *
  602. * The parameter $aliasMap is an associative array
  603. * mapping option name (short or long) to an alias.
  604. *
  605. * @param array $aliasMap
  606. * @throws Zend_Console_Getopt_Exception
  607. * @return Zend_Console_Getopt Provides a fluent interface
  608. */
  609. public function setAliases($aliasMap)
  610. {
  611. foreach ($aliasMap as $flag => $alias)
  612. {
  613. if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
  614. $flag = strtolower($flag);
  615. $alias = strtolower($alias);
  616. }
  617. if (!isset($this->_ruleMap[$flag])) {
  618. continue;
  619. }
  620. $flag = $this->_ruleMap[$flag];
  621. if (isset($this->_rules[$alias]) || isset($this->_ruleMap[$alias])) {
  622. $o = (strlen($alias) == 1 ? '-' : '--') . $alias;
  623. require_once 'Zend/Console/Getopt/Exception.php';
  624. throw new Zend_Console_Getopt_Exception(
  625. "Option \"$o\" is being defined more than once.");
  626. }
  627. $this->_rules[$flag]['alias'][] = $alias;
  628. $this->_ruleMap[$alias] = $flag;
  629. }
  630. return $this;
  631. }
  632. /**
  633. * Define help messages for options.
  634. *
  635. * The parameter $help_map is an associative array
  636. * mapping option name (short or long) to the help string.
  637. *
  638. * @param array $helpMap
  639. * @return Zend_Console_Getopt Provides a fluent interface
  640. */
  641. public function setHelp($helpMap)
  642. {
  643. foreach ($helpMap as $flag => $help)
  644. {
  645. if (!isset($this->_ruleMap[$flag])) {
  646. continue;
  647. }
  648. $flag = $this->_ruleMap[$flag];
  649. $this->_rules[$flag]['help'] = $help;
  650. }
  651. return $this;
  652. }
  653. /**
  654. * Parse command-line arguments and find both long and short
  655. * options.
  656. *
  657. * Also find option parameters, and remaining arguments after
  658. * all options have been parsed.
  659. *
  660. * @return Zend_Console_Getopt|null Provides a fluent interface
  661. */
  662. public function parse()
  663. {
  664. if ($this->_parsed === true) {
  665. return;
  666. }
  667. $argv = $this->_argv;
  668. $this->_options = array();
  669. $this->_remainingArgs = array();
  670. while (count($argv) > 0) {
  671. if ($argv[0] == '--') {
  672. array_shift($argv);
  673. if ($this->_getoptConfig[self::CONFIG_DASHDASH]) {
  674. $this->_remainingArgs = array_merge($this->_remainingArgs, $argv);
  675. break;
  676. }
  677. }
  678. if (substr($argv[0], 0, 2) == '--') {
  679. $this->_parseLongOption($argv);
  680. } else if (substr($argv[0], 0, 1) == '-' && ('-' != $argv[0] || count($argv) >1)) {
  681. $this->_parseShortOptionCluster($argv);
  682. } else if($this->_getoptConfig[self::CONFIG_PARSEALL]) {
  683. $this->_remainingArgs[] = array_shift($argv);
  684. } else {
  685. /*
  686. * We should put all other arguments in _remainingArgs and stop parsing
  687. * since CONFIG_PARSEALL is false.
  688. */
  689. $this->_remainingArgs = array_merge($this->_remainingArgs, $argv);
  690. break;
  691. }
  692. }
  693. $this->_parsed = true;
  694. return $this;
  695. }
  696. /**
  697. * Parse command-line arguments for a single long option.
  698. * A long option is preceded by a double '--' character.
  699. * Long options may not be clustered.
  700. *
  701. * @param mixed &$argv
  702. * @return void
  703. */
  704. protected function _parseLongOption(&$argv)
  705. {
  706. $optionWithParam = ltrim(array_shift($argv), '-');
  707. $l = explode('=', $optionWithParam, 2);
  708. $flag = array_shift($l);
  709. $param = array_shift($l);
  710. if (isset($param)) {
  711. array_unshift($argv, $param);
  712. }
  713. $this->_parseSingleOption($flag, $argv);
  714. }
  715. /**
  716. * Parse command-line arguments for short options.
  717. * Short options are those preceded by a single '-' character.
  718. * Short options may be clustered.
  719. *
  720. * @param mixed &$argv
  721. * @return void
  722. */
  723. protected function _parseShortOptionCluster(&$argv)
  724. {
  725. $flagCluster = ltrim(array_shift($argv), '-');
  726. foreach (str_split($flagCluster) as $flag) {
  727. $this->_parseSingleOption($flag, $argv);
  728. }
  729. }
  730. /**
  731. * Parse command-line arguments for a single option.
  732. *
  733. * @param string $flag
  734. * @param mixed $argv
  735. * @throws Zend_Console_Getopt_Exception
  736. * @return void
  737. */
  738. protected function _parseSingleOption($flag, &$argv)
  739. {
  740. if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
  741. $flag = strtolower($flag);
  742. }
  743. if (!isset($this->_ruleMap[$flag])) {
  744. require_once 'Zend/Console/Getopt/Exception.php';
  745. throw new Zend_Console_Getopt_Exception(
  746. "Option \"$flag\" is not recognized.",
  747. $this->getUsageMessage());
  748. }
  749. $realFlag = $this->_ruleMap[$flag];
  750. switch ($this->_rules[$realFlag]['param']) {
  751. case 'required':
  752. if (count($argv) > 0) {
  753. $param = array_shift($argv);
  754. $this->_checkParameterType($realFlag, $param);
  755. } else {
  756. require_once 'Zend/Console/Getopt/Exception.php';
  757. throw new Zend_Console_Getopt_Exception(
  758. "Option \"$flag\" requires a parameter.",
  759. $this->getUsageMessage());
  760. }
  761. break;
  762. case 'optional':
  763. if (count($argv) > 0 && substr($argv[0], 0, 1) != '-') {
  764. $param = array_shift($argv);
  765. $this->_checkParameterType($realFlag, $param);
  766. } else {
  767. $param = true;
  768. }
  769. break;
  770. default:
  771. $param = true;
  772. }
  773. $this->_options[$realFlag] = $param;
  774. }
  775. /**
  776. * Return true if the parameter is in a valid format for
  777. * the option $flag.
  778. * Throw an exception in most other cases.
  779. *
  780. * @param string $flag
  781. * @param string $param
  782. * @throws Zend_Console_Getopt_Exception
  783. * @return bool
  784. */
  785. protected function _checkParameterType($flag, $param)
  786. {
  787. $type = 'string';
  788. if (isset($this->_rules[$flag]['paramType'])) {
  789. $type = $this->_rules[$flag]['paramType'];
  790. }
  791. switch ($type) {
  792. case 'word':
  793. if (preg_match('/\W/', $param)) {
  794. require_once 'Zend/Console/Getopt/Exception.php';
  795. throw new Zend_Console_Getopt_Exception(
  796. "Option \"$flag\" requires a single-word parameter, but was given \"$param\".",
  797. $this->getUsageMessage());
  798. }
  799. break;
  800. case 'integer':
  801. if (preg_match('/\D/', $param)) {
  802. require_once 'Zend/Console/Getopt/Exception.php';
  803. throw new Zend_Console_Getopt_Exception(
  804. "Option \"$flag\" requires an integer parameter, but was given \"$param\".",
  805. $this->getUsageMessage());
  806. }
  807. break;
  808. case 'string':
  809. default:
  810. break;
  811. }
  812. return true;
  813. }
  814. /**
  815. * Define legal options using the gnu-style format.
  816. *
  817. * @param string $rules
  818. * @return void
  819. */
  820. protected function _addRulesModeGnu($rules)
  821. {
  822. $ruleArray = array();
  823. /**
  824. * Options may be single alphanumeric characters.
  825. * Options may have a ':' which indicates a required string parameter.
  826. * No long options or option aliases are supported in GNU style.
  827. */
  828. preg_match_all('/([a-zA-Z0-9]:?)/', $rules, $ruleArray);
  829. foreach ($ruleArray[1] as $rule) {
  830. $r = array();
  831. $flag = substr($rule, 0, 1);
  832. if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
  833. $flag = strtolower($flag);
  834. }
  835. $r['alias'][] = $flag;
  836. if (substr($rule, 1, 1) == ':') {
  837. $r['param'] = 'required';
  838. $r['paramType'] = 'string';
  839. } else {
  840. $r['param'] = 'none';
  841. }
  842. $this->_rules[$flag] = $r;
  843. $this->_ruleMap[$flag] = $flag;
  844. }
  845. }
  846. /**
  847. * Define legal options using the Zend-style format.
  848. *
  849. * @param array $rules
  850. * @throws Zend_Console_Getopt_Exception
  851. * @return void
  852. */
  853. protected function _addRulesModeZend($rules)
  854. {
  855. foreach ($rules as $ruleCode => $helpMessage)
  856. {
  857. // this may have to translate the long parm type if there
  858. // are any complaints that =string will not work (even though that use
  859. // case is not documented)
  860. if (in_array(substr($ruleCode, -2, 1), array('-', '='))) {
  861. $flagList = substr($ruleCode, 0, -2);
  862. $delimiter = substr($ruleCode, -2, 1);
  863. $paramType = substr($ruleCode, -1);
  864. } else {
  865. $flagList = $ruleCode;
  866. $delimiter = $paramType = null;
  867. }
  868. if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
  869. $flagList = strtolower($flagList);
  870. }
  871. $flags = explode('|', $flagList);
  872. $rule = array();
  873. $mainFlag = $flags[0];
  874. foreach ($flags as $flag) {
  875. if (empty($flag)) {
  876. require_once 'Zend/Console/Getopt/Exception.php';
  877. throw new Zend_Console_Getopt_Exception(
  878. "Blank flag not allowed in rule \"$ruleCode\".");
  879. }
  880. if (strlen($flag) == 1) {
  881. if (isset($this->_ruleMap[$flag])) {
  882. require_once 'Zend/Console/Getopt/Exception.php';
  883. throw new Zend_Console_Getopt_Exception(
  884. "Option \"-$flag\" is being defined more than once.");
  885. }
  886. $this->_ruleMap[$flag] = $mainFlag;
  887. $rule['alias'][] = $flag;
  888. } else {
  889. if (isset($this->_rules[$flag]) || isset($this->_ruleMap[$flag])) {
  890. require_once 'Zend/Console/Getopt/Exception.php';
  891. throw new Zend_Console_Getopt_Exception(
  892. "Option \"--$flag\" is being defined more than once.");
  893. }
  894. $this->_ruleMap[$flag] = $mainFlag;
  895. $rule['alias'][] = $flag;
  896. }
  897. }
  898. if (isset($delimiter)) {
  899. switch ($delimiter) {
  900. case self::PARAM_REQUIRED:
  901. $rule['param'] = 'required';
  902. break;
  903. case self::PARAM_OPTIONAL:
  904. default:
  905. $rule['param'] = 'optional';
  906. }
  907. switch (substr($paramType, 0, 1)) {
  908. case self::TYPE_WORD:
  909. $rule['paramType'] = 'word';
  910. break;
  911. case self::TYPE_INTEGER:
  912. $rule['paramType'] = 'integer';
  913. break;
  914. case self::TYPE_STRING:
  915. default:
  916. $rule['paramType'] = 'string';
  917. }
  918. } else {
  919. $rule['param'] = 'none';
  920. }
  921. $rule['help'] = $helpMessage;
  922. $this->_rules[$mainFlag] = $rule;
  923. }
  924. }
  925. }