PageRenderTime 46ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/library/Zend/Console/Getopt.php

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