Getopt.php 31 KB

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