Zend Framework  3.0
Public Member Functions | Public Attributes | Protected Member Functions | Protected Attributes | List of all members
Getopt Class Reference

Getopt is a class to parse options for command-line applications. More...

Public Member Functions

 __construct ($rules, $argv=null, $getoptConfig=[])
 The constructor takes one to three parameters.
 
 __get ($key)
 Return the state of the option seen on the command line of the current application invocation.
 
 __isset ($key)
 Test whether a given option has been seen.
 
 __set ($key, $value)
 Set the value for a given option.
 
 __toString ()
 Return the current set of options and parameters seen as a string.
 
 __unset ($key)
 Unset an option.
 
 addArguments ($argv)
 Define additional command-line arguments.
 
 setArguments ($argv)
 Define full set of command-line arguments.
 
 setOptions ($getoptConfig)
 Define multiple configuration options from an associative array.
 
 setOption ($configKey, $configValue)
 Define one configuration option as a key/value pair.
 
 addRules ($rules)
 Define additional option rules.
 
 toString ()
 Return the current set of options and parameters seen as a string.
 
 toArray ()
 Return the current set of options and parameters seen as an array of canonical options and parameters.
 
 toJson ()
 Return the current set of options and parameters seen in Json format.
 
 toXml ()
 Return the current set of options and parameters seen in XML format.
 
 getOptions ()
 Return a list of options that have been seen in the current argv.
 
 getOption ($flag)
 Return the state of the option seen on the command line of the current application invocation.
 
 getRemainingArgs ()
 Return the arguments from the command-line following all options found.
 
 getArguments ()
 
 getUsageMessage ()
 Return a useful option reference, formatted for display in an error message.
 
 setAliases ($aliasMap)
 Define aliases for options.
 
 setHelp ($helpMap)
 Define help messages for options.
 
 parse ()
 Parse command-line arguments and find both long and short options.
 
 setOptionCallback ($option,\Closure $callback)
 

Public Attributes

const MODE_ZEND = 'zend'
 The options for a given application can be in multiple formats.
 
const MODE_GNU = 'gnu'
 
const PARAM_REQUIRED = '='
 Constant tokens for various symbols used in the mode_zend rule format.
 
const PARAM_OPTIONAL = '-'
 
const TYPE_STRING = 's'
 
const TYPE_WORD = 'w'
 
const TYPE_INTEGER = 'i'
 
const TYPE_NUMERIC_FLAG = '#'
 
const CONFIG_RULEMODE = 'ruleMode'
 These are constants for optional behavior of this class.
 
const CONFIG_DASHDASH = 'dashDash'
 
const CONFIG_IGNORECASE = 'ignoreCase'
 
const CONFIG_PARSEALL = 'parseAll'
 
const CONFIG_CUMULATIVE_PARAMETERS = 'cumulativeParameters'
 
const CONFIG_CUMULATIVE_FLAGS = 'cumulativeFlags'
 
const CONFIG_PARAMETER_SEPARATOR = 'parameterSeparator'
 
const CONFIG_FREEFORM_FLAGS = 'freeformFlags'
 
const CONFIG_NUMERIC_FLAGS = 'numericFlags'
 

Protected Member Functions

 triggerCallbacks ()
 Triggers all the registered callbacks.
 
 _parseLongOption (&$argv)
 Parse command-line arguments for a single long option.
 
 _parseShortOptionCluster (&$argv)
 Parse command-line arguments for short options.
 
 _parseSingleOption ($flag, &$argv)
 Parse command-line arguments for a single option.
 
 _setNumericOptionValue ($value)
 Set given value as value of numeric option.
 
 _setSingleOptionValue ($flag, $value)
 Add relative to options' flag value.
 
 _setBooleanFlagValue ($flag)
 Set TRUE value to given flag, if this option does not exist yet In other case increase value to show count of flags' usage.
 
 _checkParameterType ($flag, $param)
 Return true if the parameter is in a valid format for the option $flag.
 
 _addRulesModeGnu ($rules)
 Define legal options using the gnu-style format.
 
 _addRulesModeZend ($rules)
 Define legal options using the Zend-style format.
 

Protected Attributes

 $getoptConfig
 Defaults for getopt configuration are: ruleMode is 'zend' format, dashDash (–) token is enabled, ignoreCase is not enabled, parseAll is enabled, cumulative parameters are disabled, this means that subsequent options overwrite the parameter value, cumulative flags are disable, freeform flags are disable.
 
 $argv = []
 
 $progname = ''
 
 $rules = []
 
 $ruleMap = []
 
 $options = []
 
 $remainingArgs = []
 
 $parsed = false
 
 $optionCallbacks = []
 

Detailed Description

Getopt is a class to parse options for command-line applications.

Terminology: Argument: an element of the argv array. This may be part of an option, or it may be a non-option command-line argument. Flag: the letter or word set off by a '-' or '–'. Example: in '–output filename', '–output' is the flag. Parameter: the additional argument that is associated with the option. Example: in '–output filename', the 'filename' is the parameter. Option: the combination of a flag and its parameter, if any. Example: in '–output filename', the whole thing is the option.

The following features are supported:

The format for specifying options uses a PHP associative array. The key is has the format of a list of pipe-separated flag names, followed by an optional '=' to indicate a required parameter or '-' to indicate an optional parameter. Following that, the type of parameter may be specified as 's' for string, 'w' for word, or 'i' for integer.

Examples:

The values in the associative array are strings that are used as brief descriptions of the options when printing a usage message.

The simpler format for specifying options used by PHP's getopt() function is also supported. This is similar to GNU getopt and shell getopt format.

Example: 'abc:' means options '-a', '-b', and '-c' are legal, and the latter requires a string parameter.

Constructor & Destructor Documentation

__construct (   $rules,
  $argv = null,
  $getoptConfig = [] 
)

The constructor takes one to three parameters.

The first parameter is $rules, which may be a string for gnu-style format, or a structured array for Zend-style format.

The second parameter is $argv, and it is optional. If not specified, $argv is inferred from the global argv.

The third parameter is an array of configuration parameters to control the behavior of this instance of Getopt; it is optional.

Parameters
array$rules
array$argv
array$getoptConfig
Exceptions
Exception\InvalidArgumentException

Member Function Documentation

__get (   $key)

Return the state of the option seen on the command line of the current application invocation.

This function returns true, or the parameter to the option, if any. If the option was not given, this function returns null.

The magic __get method works in the context of naming the option as a virtual member of this class.

Parameters
string$key
Returns
string
__isset (   $key)

Test whether a given option has been seen.

Parameters
string$key
Returns
bool
__set (   $key,
  $value 
)

Set the value for a given option.

Parameters
string$key
string$value
__toString ( )

Return the current set of options and parameters seen as a string.

Returns
string
__unset (   $key)

Unset an option.

Parameters
string$key
_addRulesModeGnu (   $rules)
protected

Define legal options using the gnu-style format.

Parameters
string$rules

Options may be single alphanumeric characters. Options may have a ':' which indicates a required string parameter. No long options or option aliases are supported in GNU style.

_addRulesModeZend (   $rules)
protected

Define legal options using the Zend-style format.

Parameters
array$rules
Exceptions
Exception\ExceptionInterface
_checkParameterType (   $flag,
  $param 
)
protected

Return true if the parameter is in a valid format for the option $flag.

Throw an exception in most other cases.

Parameters
string$flag
string$param
Exceptions
Exception\ExceptionInterface
Returns
bool
_parseLongOption ( $argv)
protected

Parse command-line arguments for a single long option.

A long option is preceded by a double '–' character. Long options may not be clustered.

Parameters
mixed&$argv
_parseShortOptionCluster ( $argv)
protected

Parse command-line arguments for short options.

Short options are those preceded by a single '-' character. Short options may be clustered.

Parameters
mixed&$argv
_parseSingleOption (   $flag,
$argv 
)
protected

Parse command-line arguments for a single option.

Parameters
string$flag
mixed$argv
Exceptions
Exception\ExceptionInterface
_setBooleanFlagValue (   $flag)
protected

Set TRUE value to given flag, if this option does not exist yet In other case increase value to show count of flags' usage.

Parameters
string$flag
_setNumericOptionValue (   $value)
protected

Set given value as value of numeric option.

Throw runtime exception if this action is deny by configuration or no one numeric option handlers is defined

Parameters
int$value
Exceptions
Exception\RuntimeException
Returns
void
_setSingleOptionValue (   $flag,
  $value 
)
protected

Add relative to options' flag value.

If options list already has current flag as key and parser should follow cumulative params by configuration, we should to add new param to array, not to overwrite

Parameters
string$flag
string$value
addArguments (   $argv)

Define additional command-line arguments.

These are appended to those defined when the constructor was called.

Parameters
array$argv
Exceptions
Exception\InvalidArgumentExceptionWhen not given an array as parameter
Returns
self
addRules (   $rules)

Define additional option rules.

These are appended to the rules defined when the constructor was called.

Parameters
array$rules
Returns
self

Call addRulesModeFoo() for ruleMode 'foo'. The developer should subclass Getopt and provide this method.

getArguments ( )
getOption (   $flag)

Return the state of the option seen on the command line of the current application invocation.

This function returns true, or the parameter value to the option, if any. If the option was not given, this function returns false.

Parameters
string$flag
Returns
mixed
getOptions ( )

Return a list of options that have been seen in the current argv.

Returns
array
getRemainingArgs ( )

Return the arguments from the command-line following all options found.

Returns
array
getUsageMessage ( )

Return a useful option reference, formatted for display in an error message.

Note that this usage information is provided in most Exceptions generated by this class.

Returns
string
parse ( )

Parse command-line arguments and find both long and short options.

Also find option parameters, and remaining arguments after all options have been parsed.

Returns
self
setAliases (   $aliasMap)

Define aliases for options.

The parameter $aliasMap is an associative array mapping option name (short or long) to an alias.

Parameters
array$aliasMap
Exceptions
Exception\ExceptionInterface
Returns
self
setArguments (   $argv)

Define full set of command-line arguments.

These replace any currently defined.

Parameters
array$argv
Exceptions
Exception\InvalidArgumentExceptionWhen not given an array as parameter
Returns
self
setHelp (   $helpMap)

Define help messages for options.

The parameter $helpMap is an associative array mapping option name (short or long) to the help string.

Parameters
array$helpMap
Returns
self
setOption (   $configKey,
  $configValue 
)

Define one configuration option as a key/value pair.

These are not program options, but properties to configure the behavior of Zend.

Parameters
string$configKey
string$configValue
Returns
self
setOptionCallback (   $option,
\Closure  $callback 
)
Parameters
string$optionThe name of the property which, if present, will call the passed callback with the value of this parameter.
callable$callbackThe callback that will be called for this option. The first parameter will be the value of getOption($option), the second parameter will be a reference to $this object. If the callback returns false then an Exception will be thrown indicating that there is a parse issue with this option.
Returns
self
setOptions (   $getoptConfig)

Define multiple configuration options from an associative array.

These are not program options, but properties to configure the behavior of Zend.

Parameters
array$getoptConfig
Returns
self
toArray ( )

Return the current set of options and parameters seen as an array of canonical options and parameters.

Clusters have been expanded, and option aliases have been mapped to their primary option names.

Returns
array
toJson ( )

Return the current set of options and parameters seen in Json format.

Returns
string
toString ( )

Return the current set of options and parameters seen as a string.

Returns
string
toXml ( )

Return the current set of options and parameters seen in XML format.

Returns
string
triggerCallbacks ( )
protected

Triggers all the registered callbacks.

Member Data Documentation

$argv = []
protected
$getoptConfig
protected
Initial value:
= [
self::CONFIG_RULEMODE => self::MODE_ZEND

Defaults for getopt configuration are: ruleMode is 'zend' format, dashDash (–) token is enabled, ignoreCase is not enabled, parseAll is enabled, cumulative parameters are disabled, this means that subsequent options overwrite the parameter value, cumulative flags are disable, freeform flags are disable.

$optionCallbacks = []
protected
$options = []
protected
$parsed = false
protected
$progname = ''
protected
$remainingArgs = []
protected
$ruleMap = []
protected
$rules = []
protected
const CONFIG_CUMULATIVE_FLAGS = 'cumulativeFlags'
const CONFIG_CUMULATIVE_PARAMETERS = 'cumulativeParameters'
const CONFIG_DASHDASH = 'dashDash'
const CONFIG_FREEFORM_FLAGS = 'freeformFlags'
const CONFIG_IGNORECASE = 'ignoreCase'
const CONFIG_NUMERIC_FLAGS = 'numericFlags'
const CONFIG_PARAMETER_SEPARATOR = 'parameterSeparator'
const CONFIG_PARSEALL = 'parseAll'
const CONFIG_RULEMODE = 'ruleMode'

These are constants for optional behavior of this class.

ruleMode is either 'zend' or 'gnu' or a user-defined mode. dashDash is true if '–' signifies the end of command-line options. ignoreCase is true if '–opt' and '–OPT' are implicitly synonyms. parseAll is true if all options on the command line should be parsed, regardless of whether an argument appears before them.

const MODE_GNU = 'gnu'
const MODE_ZEND = 'zend'

The options for a given application can be in multiple formats.

modeGnu is for traditional 'ab:c:' style getopt format. modeZend is for a more structured format.

const PARAM_OPTIONAL = '-'
const PARAM_REQUIRED = '='

Constant tokens for various symbols used in the mode_zend rule format.

const TYPE_INTEGER = 'i'
const TYPE_NUMERIC_FLAG = '#'
const TYPE_STRING = 's'
const TYPE_WORD = 'w'