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

/library/Zend/Console/Getopt.php

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