Added the zend framework 2 library, the path is specified in line no.26 in zend_modul...
[openemr.git] / interface / modules / zend_modules / library / Zend / Console / Getopt.php
blob617d8fd5ac11190795e53c64e52301e6b63841e2
1 <?php
2 /**
3 * Zend Framework (http://framework.zend.com/)
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 */
10 namespace Zend\Console;
12 /**
13 * Getopt is a class to parse options for command-line
14 * applications.
16 * Terminology:
17 * Argument: an element of the argv array. This may be part of an option,
18 * or it may be a non-option command-line argument.
19 * Flag: the letter or word set off by a '-' or '--'. Example: in '--output filename',
20 * '--output' is the flag.
21 * Parameter: the additional argument that is associated with the option.
22 * Example: in '--output filename', the 'filename' is the parameter.
23 * Option: the combination of a flag and its parameter, if any.
24 * Example: in '--output filename', the whole thing is the option.
26 * The following features are supported:
28 * - Short flags like '-a'. Short flags are preceded by a single
29 * dash. Short flags may be clustered e.g. '-abc', which is the
30 * same as '-a' '-b' '-c'.
31 * - Long flags like '--verbose'. Long flags are preceded by a
32 * double dash. Long flags may not be clustered.
33 * - Options may have a parameter, e.g. '--output filename'.
34 * - Parameters for long flags may also be set off with an equals sign,
35 * e.g. '--output=filename'.
36 * - Parameters for long flags may be checked as string, word, or integer.
37 * - Automatic generation of a helpful usage message.
38 * - Signal end of options with '--'; subsequent arguments are treated
39 * as non-option arguments, even if they begin with '-'.
40 * - Raise exception Zend_Console_Getopt_Exception in several cases
41 * when invalid flags or parameters are given. Usage message is
42 * returned in the exception object.
44 * The format for specifying options uses a PHP associative array.
45 * The key is has the format of a list of pipe-separated flag names,
46 * followed by an optional '=' to indicate a required parameter or
47 * '-' to indicate an optional parameter. Following that, the type
48 * of parameter may be specified as 's' for string, 'w' for word,
49 * or 'i' for integer.
51 * Examples:
52 * - 'user|username|u=s' this means '--user' or '--username' or '-u'
53 * are synonyms, and the option requires a string parameter.
54 * - 'p=i' this means '-p' requires an integer parameter. No synonyms.
55 * - 'verbose|v-i' this means '--verbose' or '-v' are synonyms, and
56 * they take an optional integer parameter.
57 * - 'help|h' this means '--help' or '-h' are synonyms, and
58 * they take no parameter.
60 * The values in the associative array are strings that are used as
61 * brief descriptions of the options when printing a usage message.
63 * The simpler format for specifying options used by PHP's getopt()
64 * function is also supported. This is similar to GNU getopt and shell
65 * getopt format.
67 * Example: 'abc:' means options '-a', '-b', and '-c'
68 * are legal, and the latter requires a string parameter.
70 * @todo Handle flags that implicitly print usage message, e.g. --help
72 * @todo Enable user to specify header and footer content in the help message.
74 * @todo Feature request to handle option interdependencies.
75 * e.g. if -b is specified, -a must be specified or else the
76 * usage is invalid.
78 * @todo Feature request to implement callbacks.
79 * e.g. if -a is specified, run function 'handleOptionA'().
81 class Getopt
84 /**
85 * The options for a given application can be in multiple formats.
86 * modeGnu is for traditional 'ab:c:' style getopt format.
87 * modeZend is for a more structured format.
89 const MODE_ZEND = 'zend';
90 const MODE_GNU = 'gnu';
92 /**
93 * Constant tokens for various symbols used in the mode_zend
94 * rule format.
96 const PARAM_REQUIRED = '=';
97 const PARAM_OPTIONAL = '-';
98 const TYPE_STRING = 's';
99 const TYPE_WORD = 'w';
100 const TYPE_INTEGER = 'i';
101 const TYPE_NUMERIC_FLAG = '#';
104 * These are constants for optional behavior of this class.
105 * ruleMode is either 'zend' or 'gnu' or a user-defined mode.
106 * dashDash is true if '--' signifies the end of command-line options.
107 * ignoreCase is true if '--opt' and '--OPT' are implicitly synonyms.
108 * parseAll is true if all options on the command line should be parsed, regardless of
109 * whether an argument appears before them.
111 const CONFIG_RULEMODE = 'ruleMode';
112 const CONFIG_DASHDASH = 'dashDash';
113 const CONFIG_IGNORECASE = 'ignoreCase';
114 const CONFIG_PARSEALL = 'parseAll';
115 const CONFIG_CUMULATIVE_PARAMETERS = 'cumulativeParameters';
116 const CONFIG_CUMULATIVE_FLAGS = 'cumulativeFlags';
117 const CONFIG_PARAMETER_SEPARATOR = 'parameterSeparator';
118 const CONFIG_FREEFORM_FLAGS = 'freeformFlags';
119 const CONFIG_NUMERIC_FLAGS = 'numericFlags';
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.
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
145 * Stores the command-line arguments for the calling application.
147 * @var array
149 protected $argv = array();
152 * Stores the name of the calling application.
154 * @var string
156 protected $progname = '';
159 * Stores the list of legal options for this application.
161 * @var array
163 protected $rules = array();
166 * Stores alternate spellings of legal options.
168 * @var array
170 protected $ruleMap = array();
173 * Stores options given by the user in the current invocation
174 * of the application, as well as parameters given in options.
176 * @var array
178 protected $options = array();
181 * Stores the command-line arguments other than options.
183 * @var array
185 protected $remainingArgs = array();
188 * State of the options: parsed or not yet parsed?
190 * @var bool
192 protected $parsed = false;
195 * The constructor takes one to three parameters.
197 * The first parameter is $rules, which may be a string for
198 * gnu-style format, or a structured array for Zend-style format.
200 * The second parameter is $argv, and it is optional. If not
201 * specified, $argv is inferred from the global argv.
203 * The third parameter is an array of configuration parameters
204 * to control the behavior of this instance of Getopt; it is optional.
206 * @param array $rules
207 * @param array $argv
208 * @param array $getoptConfig
209 * @throws Exception\InvalidArgumentException
211 public function __construct($rules, $argv = null, $getoptConfig = array())
213 if (!isset($_SERVER['argv'])) {
214 $errorDescription = (ini_get('register_argc_argv') == false)
215 ? "argv is not available, because ini option 'register_argc_argv' is set Off"
216 : '$_SERVER["argv"] is not set, but Zend_Console_Getopt cannot work without this information.';
217 throw new Exception\InvalidArgumentException($errorDescription);
220 $this->progname = $_SERVER['argv'][0];
221 $this->setOptions($getoptConfig);
222 $this->addRules($rules);
223 if (!is_array($argv)) {
224 $argv = array_slice($_SERVER['argv'], 1);
226 if (isset($argv)) {
227 $this->addArguments((array) $argv);
232 * Return the state of the option seen on the command line of the
233 * current application invocation. This function returns true, or the
234 * parameter to the option, if any. If the option was not given,
235 * this function returns null.
237 * The magic __get method works in the context of naming the option
238 * as a virtual member of this class.
240 * @param string $key
241 * @return string
243 public function __get($key)
245 return $this->getOption($key);
249 * Test whether a given option has been seen.
251 * @param string $key
252 * @return bool
254 public function __isset($key)
256 $this->parse();
257 if (isset($this->ruleMap[$key])) {
258 $key = $this->ruleMap[$key];
259 return isset($this->options[$key]);
261 return false;
265 * Set the value for a given option.
267 * @param string $key
268 * @param string $value
269 * @return void
271 public function __set($key, $value)
273 $this->parse();
274 if (isset($this->ruleMap[$key])) {
275 $key = $this->ruleMap[$key];
276 $this->options[$key] = $value;
281 * Return the current set of options and parameters seen as a string.
283 * @return string
285 public function __toString()
287 return $this->toString();
291 * Unset an option.
293 * @param string $key
294 * @return void
296 public function __unset($key)
298 $this->parse();
299 if (isset($this->ruleMap[$key])) {
300 $key = $this->ruleMap[$key];
301 unset($this->options[$key]);
306 * Define additional command-line arguments.
307 * These are appended to those defined when the constructor was called.
309 * @param array $argv
310 * @throws \Zend\Console\Exception\InvalidArgumentException When not given an array as parameter
311 * @return \Zend\Console\Getopt Provides a fluent interface
313 public function addArguments($argv)
315 if (!is_array($argv)) {
316 throw new Exception\InvalidArgumentException("Parameter #1 to addArguments should be an array");
318 $this->argv = array_merge($this->argv, $argv);
319 $this->parsed = false;
320 return $this;
324 * Define full set of command-line arguments.
325 * These replace any currently defined.
327 * @param array $argv
328 * @throws \Zend\Console\Exception\InvalidArgumentException When not given an array as parameter
329 * @return \Zend\Console\Getopt Provides a fluent interface
331 public function setArguments($argv)
333 if (!is_array($argv)) {
334 throw new Exception\InvalidArgumentException("Parameter #1 to setArguments should be an array");
336 $this->argv = $argv;
337 $this->parsed = false;
338 return $this;
342 * Define multiple configuration options from an associative array.
343 * These are not program options, but properties to configure
344 * the behavior of Zend\Console\Getopt.
346 * @param array $getoptConfig
347 * @return \Zend\Console\Getopt Provides a fluent interface
349 public function setOptions($getoptConfig)
351 if (isset($getoptConfig)) {
352 foreach ($getoptConfig as $key => $value) {
353 $this->setOption($key, $value);
356 return $this;
360 * Define one configuration option as a key/value pair.
361 * These are not program options, but properties to configure
362 * the behavior of Zend\Console\Getopt.
364 * @param string $configKey
365 * @param string $configValue
366 * @return \Zend\Console\Getopt Provides a fluent interface
368 public function setOption($configKey, $configValue)
370 if ($configKey !== null) {
371 $this->getoptConfig[$configKey] = $configValue;
373 return $this;
377 * Define additional option rules.
378 * These are appended to the rules defined when the constructor was called.
380 * @param array $rules
381 * @return \Zend\Console\Getopt Provides a fluent interface
383 public function addRules($rules)
385 $ruleMode = $this->getoptConfig['ruleMode'];
386 switch ($this->getoptConfig['ruleMode']) {
387 case self::MODE_ZEND:
388 if (is_array($rules)) {
389 $this->_addRulesModeZend($rules);
390 break;
392 // intentional fallthrough
393 case self::MODE_GNU:
394 $this->_addRulesModeGnu($rules);
395 break;
396 default:
398 * Call addRulesModeFoo() for ruleMode 'foo'.
399 * The developer should subclass Getopt and
400 * provide this method.
402 $method = '_addRulesMode' . ucfirst($ruleMode);
403 $this->$method($rules);
405 $this->parsed = false;
406 return $this;
410 * Return the current set of options and parameters seen as a string.
412 * @return string
414 public function toString()
416 $this->parse();
417 $s = array();
418 foreach ($this->options as $flag => $value) {
419 $s[] = $flag . '=' . ($value === true ? 'true' : $value);
421 return implode(' ', $s);
425 * Return the current set of options and parameters seen
426 * as an array of canonical options and parameters.
428 * Clusters have been expanded, and option aliases
429 * have been mapped to their primary option names.
431 * @return array
433 public function toArray()
435 $this->parse();
436 $s = array();
437 foreach ($this->options as $flag => $value) {
438 $s[] = $flag;
439 if ($value !== true) {
440 $s[] = $value;
443 return $s;
447 * Return the current set of options and parameters seen in Json format.
449 * @return string
451 public function toJson()
453 $this->parse();
454 $j = array();
455 foreach ($this->options as $flag => $value) {
456 $j['options'][] = array(
457 'option' => array(
458 'flag' => $flag,
459 'parameter' => $value
464 $json = \Zend\Json\Json::encode($j);
465 return $json;
469 * Return the current set of options and parameters seen in XML format.
471 * @return string
473 public function toXml()
475 $this->parse();
476 $doc = new \DomDocument('1.0', 'utf-8');
477 $optionsNode = $doc->createElement('options');
478 $doc->appendChild($optionsNode);
479 foreach ($this->options as $flag => $value) {
480 $optionNode = $doc->createElement('option');
481 $optionNode->setAttribute('flag', utf8_encode($flag));
482 if ($value !== true) {
483 $optionNode->setAttribute('parameter', utf8_encode($value));
485 $optionsNode->appendChild($optionNode);
487 $xml = $doc->saveXML();
488 return $xml;
492 * Return a list of options that have been seen in the current argv.
494 * @return array
496 public function getOptions()
498 $this->parse();
499 return array_keys($this->options);
503 * Return the state of the option seen on the command line of the
504 * current application invocation.
506 * This function returns true, or the parameter value to the option, if any.
507 * If the option was not given, this function returns false.
509 * @param string $flag
510 * @return mixed
512 public function getOption($flag)
514 $this->parse();
515 if ($this->getoptConfig[self::CONFIG_IGNORECASE]) {
516 $flag = strtolower($flag);
518 if (isset($this->ruleMap[$flag])) {
519 $flag = $this->ruleMap[$flag];
520 if (isset($this->options[$flag])) {
521 return $this->options[$flag];
524 return null;
528 * Return the arguments from the command-line following all options found.
530 * @return array
532 public function getRemainingArgs()
534 $this->parse();
535 return $this->remainingArgs;
538 public function getArguments()
540 $result = $this->getRemainingArgs();
541 foreach ($this->getOptions() as $option) {
542 $result[$option] = $this->getOption($option);
544 return $result;
548 * Return a useful option reference, formatted for display in an
549 * error message.
551 * Note that this usage information is provided in most Exceptions
552 * generated by this class.
554 * @return string
556 public function getUsageMessage()
558 $usage = "Usage: {$this->progname} [ options ]\n";
559 $maxLen = 20;
560 $lines = array();
561 foreach ($this->rules as $rule) {
562 if (isset($rule['isFreeformFlag'])) {
563 continue;
565 $flags = array();
566 if (is_array($rule['alias'])) {
567 foreach ($rule['alias'] as $flag) {
568 $flags[] = (strlen($flag) == 1 ? '-' : '--') . $flag;
571 $linepart['name'] = implode('|', $flags);
572 if (isset($rule['param']) && $rule['param'] != 'none') {
573 $linepart['name'] .= ' ';
574 switch ($rule['param']) {
575 case 'optional':
576 $linepart['name'] .= "[ <{$rule['paramType']}> ]";
577 break;
578 case 'required':
579 $linepart['name'] .= "<{$rule['paramType']}>";
580 break;
583 if (strlen($linepart['name']) > $maxLen) {
584 $maxLen = strlen($linepart['name']);
586 $linepart['help'] = '';
587 if (isset($rule['help'])) {
588 $linepart['help'] .= $rule['help'];
590 $lines[] = $linepart;
592 foreach ($lines as $linepart) {
593 $usage .= sprintf("%s %s\n",
594 str_pad($linepart['name'], $maxLen),
595 $linepart['help']);
597 return $usage;
601 * Define aliases for options.
603 * The parameter $aliasMap is an associative array
604 * mapping option name (short or long) to an alias.
606 * @param array $aliasMap
607 * @throws \Zend\Console\Exception\ExceptionInterface
608 * @return \Zend\Console\Getopt Provides a fluent interface
610 public function setAliases($aliasMap)
612 foreach ($aliasMap as $flag => $alias) {
613 if ($this->getoptConfig[self::CONFIG_IGNORECASE]) {
614 $flag = strtolower($flag);
615 $alias = strtolower($alias);
617 if (!isset($this->ruleMap[$flag])) {
618 continue;
620 $flag = $this->ruleMap[$flag];
621 if (isset($this->rules[$alias]) || isset($this->ruleMap[$alias])) {
622 $o = (strlen($alias) == 1 ? '-' : '--') . $alias;
623 throw new Exception\InvalidArgumentException("Option \"$o\" is being defined more than once.");
625 $this->rules[$flag]['alias'][] = $alias;
626 $this->ruleMap[$alias] = $flag;
628 return $this;
632 * Define help messages for options.
634 * The parameter $helpMap is an associative array
635 * mapping option name (short or long) to the help string.
637 * @param array $helpMap
638 * @return \Zend\Console\Getopt Provides a fluent interface
640 public function setHelp($helpMap)
642 foreach ($helpMap as $flag => $help) {
643 if (!isset($this->ruleMap[$flag])) {
644 continue;
646 $flag = $this->ruleMap[$flag];
647 $this->rules[$flag]['help'] = $help;
649 return $this;
653 * Parse command-line arguments and find both long and short
654 * options.
656 * Also find option parameters, and remaining arguments after
657 * all options have been parsed.
659 * @return \Zend\Console\Getopt|null Provides a fluent interface
661 public function parse()
663 if ($this->parsed === true) {
664 return;
666 $argv = $this->argv;
667 $this->options = array();
668 $this->remainingArgs = array();
669 while (count($argv) > 0) {
670 if ($argv[0] == '--') {
671 array_shift($argv);
672 if ($this->getoptConfig[self::CONFIG_DASHDASH]) {
673 $this->remainingArgs = array_merge($this->remainingArgs, $argv);
674 break;
677 if (substr($argv[0], 0, 2) == '--') {
678 $this->_parseLongOption($argv);
679 } elseif (substr($argv[0], 0, 1) == '-' && ('-' != $argv[0] || count($argv) >1)) {
680 $this->_parseShortOptionCluster($argv);
681 } elseif ($this->getoptConfig[self::CONFIG_PARSEALL]) {
682 $this->remainingArgs[] = array_shift($argv);
683 } else {
685 * We should put all other arguments in remainingArgs and stop parsing
686 * since CONFIG_PARSEALL is false.
688 $this->remainingArgs = array_merge($this->remainingArgs, $argv);
689 break;
692 $this->parsed = true;
693 return $this;
697 * Parse command-line arguments for a single long option.
698 * A long option is preceded by a double '--' character.
699 * Long options may not be clustered.
701 * @param mixed &$argv
702 * @return void
704 protected function _parseLongOption(&$argv)
706 $optionWithParam = ltrim(array_shift($argv), '-');
707 $l = explode('=', $optionWithParam, 2);
708 $flag = array_shift($l);
709 $param = array_shift($l);
710 if (isset($param)) {
711 array_unshift($argv, $param);
713 $this->_parseSingleOption($flag, $argv);
717 * Parse command-line arguments for short options.
718 * Short options are those preceded by a single '-' character.
719 * Short options may be clustered.
721 * @param mixed &$argv
722 * @return void
724 protected function _parseShortOptionCluster(&$argv)
726 $flagCluster = ltrim(array_shift($argv), '-');
727 foreach (str_split($flagCluster) as $flag) {
728 $this->_parseSingleOption($flag, $argv);
733 * Parse command-line arguments for a single option.
735 * @param string $flag
736 * @param mixed $argv
737 * @throws \Zend\Console\Exception\ExceptionInterface
738 * @return void
740 protected function _parseSingleOption($flag, &$argv)
742 if ($this->getoptConfig[self::CONFIG_IGNORECASE]) {
743 $flag = strtolower($flag);
746 // Check if this option is numeric one
747 if (preg_match('/^\d+$/', $flag)) {
748 return $this->_setNumericOptionValue($flag);
751 if (!isset($this->ruleMap[$flag])) {
752 // Don't throw Exception for flag-like param in case when freeform flags are allowed
753 if (!$this->getoptConfig[self::CONFIG_FREEFORM_FLAGS]) {
754 throw new Exception\RuntimeException(
755 "Option \"$flag\" is not recognized.",
756 $this->getUsageMessage()
760 // Magic methods in future will use this mark as real flag value
761 $this->ruleMap[$flag] = $flag;
762 $realFlag = $flag;
763 $this->rules[$realFlag] = array(
764 'param' => 'optional',
765 'isFreeformFlag' => true
767 } else {
768 $realFlag = $this->ruleMap[$flag];
771 switch ($this->rules[$realFlag]['param']) {
772 case 'required':
773 if (count($argv) > 0) {
774 $param = array_shift($argv);
775 $this->_checkParameterType($realFlag, $param);
776 } else {
777 throw new Exception\RuntimeException(
778 "Option \"$flag\" requires a parameter.",
779 $this->getUsageMessage()
782 break;
783 case 'optional':
784 if (count($argv) > 0 && substr($argv[0], 0, 1) != '-') {
785 $param = array_shift($argv);
786 $this->_checkParameterType($realFlag, $param);
787 } else {
788 $param = true;
790 break;
791 default:
792 $param = true;
795 $this->_setSingleOptionValue($realFlag, $param);
800 * Set given value as value of numeric option
802 * Throw runtime exception if this action is deny by configuration
803 * or no one numeric option handlers is defined
805 * @param int $value
806 * @throws Exception\RuntimeException
807 * @return void
809 protected function _setNumericOptionValue($value)
811 if (!$this->getoptConfig[self::CONFIG_NUMERIC_FLAGS]) {
812 throw new Exception\RuntimeException("Using of numeric flags are deny by configuration");
815 if (empty($this->getoptConfig['numericFlagsOption'])) {
816 throw new Exception\RuntimeException("Any option for handling numeric flags are specified");
819 return $this->_setSingleOptionValue($this->getoptConfig['numericFlagsOption'], $value);
823 * Add relative to options' flag value
825 * If options list already has current flag as key
826 * and parser should follow cumulative params by configuration,
827 * we should to add new param to array, not to overwrite
829 * @param string $flag
830 * @param string $value
831 * @return null
833 protected function _setSingleOptionValue($flag, $value)
835 if (true === $value && $this->getoptConfig[self::CONFIG_CUMULATIVE_FLAGS]) {
836 // For boolean values we have to create new flag, or increase number of flags' usage count
837 return $this->_setBooleanFlagValue($flag);
840 // Split multiple values, if necessary
841 // Filter empty values from splited array
842 $separator = $this->getoptConfig[self::CONFIG_PARAMETER_SEPARATOR];
843 if (is_string($value) && !empty($separator) && is_string($separator) && substr_count($value, $separator)) {
844 $value = array_filter(explode($separator, $value));
847 if (!array_key_exists($flag, $this->options)) {
848 $this->options[$flag] = $value;
849 } elseif ($this->getoptConfig[self::CONFIG_CUMULATIVE_PARAMETERS]) {
850 $this->options[$flag] = (array) $this->options[$flag];
851 array_push($this->options[$flag], $value);
852 } else {
853 $this->options[$flag] = $value;
858 * Set TRUE value to given flag, if this option does not exist yet
859 * In other case increase value to show count of flags' usage
861 * @param string $flag
862 * @return null
864 protected function _setBooleanFlagValue($flag)
866 $this->options[$flag] = array_key_exists($flag, $this->options)
867 ? (int) $this->options[$flag] + 1
868 : true;
872 * Return true if the parameter is in a valid format for
873 * the option $flag.
874 * Throw an exception in most other cases.
876 * @param string $flag
877 * @param string $param
878 * @throws \Zend\Console\Exception\ExceptionInterface
879 * @return bool
881 protected function _checkParameterType($flag, $param)
883 $type = 'string';
884 if (isset($this->rules[$flag]['paramType'])) {
885 $type = $this->rules[$flag]['paramType'];
887 switch ($type) {
888 case 'word':
889 if (preg_match('/\W/', $param)) {
890 throw new Exception\RuntimeException(
891 "Option \"$flag\" requires a single-word parameter, but was given \"$param\".",
892 $this->getUsageMessage());
894 break;
895 case 'integer':
896 if (preg_match('/\D/', $param)) {
897 throw new Exception\RuntimeException(
898 "Option \"$flag\" requires an integer parameter, but was given \"$param\".",
899 $this->getUsageMessage());
901 break;
902 case 'string':
903 default:
904 break;
906 return true;
910 * Define legal options using the gnu-style format.
912 * @param string $rules
913 * @return void
915 protected function _addRulesModeGnu($rules)
917 $ruleArray = array();
920 * Options may be single alphanumeric characters.
921 * Options may have a ':' which indicates a required string parameter.
922 * No long options or option aliases are supported in GNU style.
924 preg_match_all('/([a-zA-Z0-9]:?)/', $rules, $ruleArray);
925 foreach ($ruleArray[1] as $rule) {
926 $r = array();
927 $flag = substr($rule, 0, 1);
928 if ($this->getoptConfig[self::CONFIG_IGNORECASE]) {
929 $flag = strtolower($flag);
931 $r['alias'][] = $flag;
932 if (substr($rule, 1, 1) == ':') {
933 $r['param'] = 'required';
934 $r['paramType'] = 'string';
935 } else {
936 $r['param'] = 'none';
938 $this->rules[$flag] = $r;
939 $this->ruleMap[$flag] = $flag;
944 * Define legal options using the Zend-style format.
946 * @param array $rules
947 * @throws \Zend\Console\Exception\ExceptionInterface
948 * @return void
950 protected function _addRulesModeZend($rules)
952 foreach ($rules as $ruleCode => $helpMessage) {
953 // this may have to translate the long parm type if there
954 // are any complaints that =string will not work (even though that use
955 // case is not documented)
956 if (in_array(substr($ruleCode, -2, 1), array('-', '='))) {
957 $flagList = substr($ruleCode, 0, -2);
958 $delimiter = substr($ruleCode, -2, 1);
959 $paramType = substr($ruleCode, -1);
960 } else {
961 $flagList = $ruleCode;
962 $delimiter = $paramType = null;
964 if ($this->getoptConfig[self::CONFIG_IGNORECASE]) {
965 $flagList = strtolower($flagList);
967 $flags = explode('|', $flagList);
968 $rule = array();
969 $mainFlag = $flags[0];
970 foreach ($flags as $flag) {
971 if (empty($flag)) {
972 throw new Exception\InvalidArgumentException("Blank flag not allowed in rule \"$ruleCode\".");
974 if (strlen($flag) == 1) {
975 if (isset($this->ruleMap[$flag])) {
976 throw new Exception\InvalidArgumentException(
977 "Option \"-$flag\" is being defined more than once.");
979 $this->ruleMap[$flag] = $mainFlag;
980 $rule['alias'][] = $flag;
981 } else {
982 if (isset($this->rules[$flag]) || isset($this->ruleMap[$flag])) {
983 throw new Exception\InvalidArgumentException(
984 "Option \"--$flag\" is being defined more than once.");
986 $this->ruleMap[$flag] = $mainFlag;
987 $rule['alias'][] = $flag;
990 if (isset($delimiter)) {
991 switch ($delimiter) {
992 case self::PARAM_REQUIRED:
993 $rule['param'] = 'required';
994 break;
995 case self::PARAM_OPTIONAL:
996 default:
997 $rule['param'] = 'optional';
999 switch (substr($paramType, 0, 1)) {
1000 case self::TYPE_WORD:
1001 $rule['paramType'] = 'word';
1002 break;
1003 case self::TYPE_INTEGER:
1004 $rule['paramType'] = 'integer';
1005 break;
1006 case self::TYPE_NUMERIC_FLAG:
1007 $rule['paramType'] = 'numericFlag';
1008 $this->getoptConfig['numericFlagsOption'] = $mainFlag;
1009 break;
1010 case self::TYPE_STRING:
1011 default:
1012 $rule['paramType'] = 'string';
1014 } else {
1015 $rule['param'] = 'none';
1017 $rule['help'] = $helpMessage;
1018 $this->rules[$mainFlag] = $rule;