PageRenderTime 58ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/dev/tools/Magento/Tools/I18n/Zend/Console/Getopt.php

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