PageRenderTime 64ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 0ms

/monica/vendor/zendframework/zendframework/library/Zend/Console/Getopt.php

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