PageRenderTime 68ms CodeModel.GetById 29ms RepoModel.GetById 1ms app.codeStats 0ms

/application/libraries/Zend/Console/Getopt.php

https://github.com/AppStateLibrary/omeka
PHP | 992 lines | 517 code | 46 blank | 429 comment | 86 complexity | 4bf730406e99629e4031c6c407cdf4f2 MD5 | raw file
Possible License(s): AGPL-3.0, LGPL-2.1, MPL-2.0-no-copyleft-exception, Apache-2.0, GPL-3.0
  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-2015 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-2015 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 application.
  171. *
  172. * @var array
  173. */
  174. protected $_argv = array();
  175. /**
  176. * Stores the name of the calling application.
  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 null.
  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. * @throws Zend_Console_Getopt_Exception
  698. */
  699. public function checkRequiredArguments()
  700. {
  701. foreach ($this->_rules as $name => $rule) {
  702. if ($rule['param'] === 'required') {
  703. $defined = false;
  704. foreach ($rule['alias'] as $alias) {
  705. $defined = $defined === true ? true : array_key_exists($alias, $this->_options);
  706. }
  707. if ($defined === false) {
  708. require_once 'Zend/Console/Getopt/Exception.php';
  709. throw new Zend_Console_Getopt_Exception(
  710. 'Option "$alias" requires a parameter.',
  711. $this->getUsageMessage()
  712. );
  713. }
  714. }
  715. }
  716. }
  717. /**
  718. * Parse command-line arguments for a single long option.
  719. * A long option is preceded by a double '--' character.
  720. * Long options may not be clustered.
  721. *
  722. * @param mixed &$argv
  723. * @return void
  724. */
  725. protected function _parseLongOption(&$argv)
  726. {
  727. $optionWithParam = ltrim(array_shift($argv), '-');
  728. $l = explode('=', $optionWithParam, 2);
  729. $flag = array_shift($l);
  730. $param = array_shift($l);
  731. if (isset($param)) {
  732. array_unshift($argv, $param);
  733. }
  734. $this->_parseSingleOption($flag, $argv);
  735. }
  736. /**
  737. * Parse command-line arguments for short options.
  738. * Short options are those preceded by a single '-' character.
  739. * Short options may be clustered.
  740. *
  741. * @param mixed &$argv
  742. * @return void
  743. */
  744. protected function _parseShortOptionCluster(&$argv)
  745. {
  746. $flagCluster = ltrim(array_shift($argv), '-');
  747. foreach (str_split($flagCluster) as $flag) {
  748. $this->_parseSingleOption($flag, $argv);
  749. }
  750. }
  751. /**
  752. * Parse command-line arguments for a single option.
  753. *
  754. * @param string $flag
  755. * @param mixed $argv
  756. * @throws Zend_Console_Getopt_Exception
  757. * @return void
  758. */
  759. protected function _parseSingleOption($flag, &$argv)
  760. {
  761. if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
  762. $flag = strtolower($flag);
  763. }
  764. if (!isset($this->_ruleMap[$flag])) {
  765. require_once 'Zend/Console/Getopt/Exception.php';
  766. throw new Zend_Console_Getopt_Exception(
  767. "Option \"$flag\" is not recognized.",
  768. $this->getUsageMessage());
  769. }
  770. $realFlag = $this->_ruleMap[$flag];
  771. switch ($this->_rules[$realFlag]['param']) {
  772. case 'required':
  773. if (count($argv) > 0 && substr($argv[0], 0, 1) != '-') {
  774. $param = array_shift($argv);
  775. $this->_checkParameterType($realFlag, $param);
  776. } else {
  777. require_once 'Zend/Console/Getopt/Exception.php';
  778. throw new Zend_Console_Getopt_Exception(
  779. "Option \"$flag\" requires a parameter.",
  780. $this->getUsageMessage());
  781. }
  782. break;
  783. case 'optional':
  784. if (count($argv) > 0 && substr($argv[0], 0, 1) != '-') {
  785. $param = array_shift($argv);
  786. $this->_checkParameterType($realFlag, $param);
  787. } else {
  788. $param = true;
  789. }
  790. break;
  791. default:
  792. $param = true;
  793. }
  794. $this->_options[$realFlag] = $param;
  795. }
  796. /**
  797. * Return true if the parameter is in a valid format for
  798. * the option $flag.
  799. * Throw an exception in most other cases.
  800. *
  801. * @param string $flag
  802. * @param string $param
  803. * @throws Zend_Console_Getopt_Exception
  804. * @return bool
  805. */
  806. protected function _checkParameterType($flag, $param)
  807. {
  808. $type = 'string';
  809. if (isset($this->_rules[$flag]['paramType'])) {
  810. $type = $this->_rules[$flag]['paramType'];
  811. }
  812. switch ($type) {
  813. case 'word':
  814. if (preg_match('/\W/', $param)) {
  815. require_once 'Zend/Console/Getopt/Exception.php';
  816. throw new Zend_Console_Getopt_Exception(
  817. "Option \"$flag\" requires a single-word parameter, but was given \"$param\".",
  818. $this->getUsageMessage());
  819. }
  820. break;
  821. case 'integer':
  822. if (preg_match('/\D/', $param)) {
  823. require_once 'Zend/Console/Getopt/Exception.php';
  824. throw new Zend_Console_Getopt_Exception(
  825. "Option \"$flag\" requires an integer parameter, but was given \"$param\".",
  826. $this->getUsageMessage());
  827. }
  828. break;
  829. case 'string':
  830. default:
  831. break;
  832. }
  833. return true;
  834. }
  835. /**
  836. * Define legal options using the gnu-style format.
  837. *
  838. * @param string $rules
  839. * @return void
  840. */
  841. protected function _addRulesModeGnu($rules)
  842. {
  843. $ruleArray = array();
  844. /**
  845. * Options may be single alphanumeric characters.
  846. * Options may have a ':' which indicates a required string parameter.
  847. * No long options or option aliases are supported in GNU style.
  848. */
  849. preg_match_all('/([a-zA-Z0-9]:?)/', $rules, $ruleArray);
  850. foreach ($ruleArray[1] as $rule) {
  851. $r = array();
  852. $flag = substr($rule, 0, 1);
  853. if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
  854. $flag = strtolower($flag);
  855. }
  856. $r['alias'][] = $flag;
  857. if (substr($rule, 1, 1) == ':') {
  858. $r['param'] = 'required';
  859. $r['paramType'] = 'string';
  860. } else {
  861. $r['param'] = 'none';
  862. }
  863. $this->_rules[$flag] = $r;
  864. $this->_ruleMap[$flag] = $flag;
  865. }
  866. }
  867. /**
  868. * Define legal options using the Zend-style format.
  869. *
  870. * @param array $rules
  871. * @throws Zend_Console_Getopt_Exception
  872. * @return void
  873. */
  874. protected function _addRulesModeZend($rules)
  875. {
  876. foreach ($rules as $ruleCode => $helpMessage)
  877. {
  878. // this may have to translate the long parm type if there
  879. // are any complaints that =string will not work (even though that use
  880. // case is not documented)
  881. if (in_array(substr($ruleCode, -2, 1), array('-', '='))) {
  882. $flagList = substr($ruleCode, 0, -2);
  883. $delimiter = substr($ruleCode, -2, 1);
  884. $paramType = substr($ruleCode, -1);
  885. } else {
  886. $flagList = $ruleCode;
  887. $delimiter = $paramType = null;
  888. }
  889. if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
  890. $flagList = strtolower($flagList);
  891. }
  892. $flags = explode('|', $flagList);
  893. $rule = array();
  894. $mainFlag = $flags[0];
  895. foreach ($flags as $flag) {
  896. if (empty($flag)) {
  897. require_once 'Zend/Console/Getopt/Exception.php';
  898. throw new Zend_Console_Getopt_Exception(
  899. "Blank flag not allowed in rule \"$ruleCode\".");
  900. }
  901. if (strlen($flag) == 1) {
  902. if (isset($this->_ruleMap[$flag])) {
  903. require_once 'Zend/Console/Getopt/Exception.php';
  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. require_once 'Zend/Console/Getopt/Exception.php';
  912. throw new Zend_Console_Getopt_Exception(
  913. "Option \"--$flag\" is being defined more than once.");
  914. }
  915. $this->_ruleMap[$flag] = $mainFlag;
  916. $rule['alias'][] = $flag;
  917. }
  918. }
  919. if (isset($delimiter)) {
  920. switch ($delimiter) {
  921. case self::PARAM_REQUIRED:
  922. $rule['param'] = 'required';
  923. break;
  924. case self::PARAM_OPTIONAL:
  925. default:
  926. $rule['param'] = 'optional';
  927. }
  928. switch (substr($paramType, 0, 1)) {
  929. case self::TYPE_WORD:
  930. $rule['paramType'] = 'word';
  931. break;
  932. case self::TYPE_INTEGER:
  933. $rule['paramType'] = 'integer';
  934. break;
  935. case self::TYPE_STRING:
  936. default:
  937. $rule['paramType'] = 'string';
  938. }
  939. } else {
  940. $rule['param'] = 'none';
  941. }
  942. $rule['help'] = $helpMessage;
  943. $this->_rules[$mainFlag] = $rule;
  944. }
  945. }
  946. }