ConsoleOptionParser
in package
Handles parsing the ARGV in the command line and provides support for GetOpt compatible option definition. Provides a builder pattern implementation for creating shell option parsers.
Options
Named arguments come in two forms, long and short. Long arguments are preceded
by two - and give a more verbose option name. i.e. --version
. Short arguments are
preceded by one - and are only one character long. They usually match with a long option,
and provide a more terse alternative.
Using Options
Options can be defined with both long and short forms. By using $parser->addOption()
you can define new options. The name of the option is used as its long form, and you
can supply an additional short form, with the short
option. Short options should
only be one letter long. Using more than one letter for a short option will raise an exception.
Calling options can be done using syntax similar to most *nix command line tools. Long options
cane either include an =
or leave it out.
cake my_command --connection default --name=something
Short options can be defined singly or in groups.
cake my_command -cn
Short options can be combined into groups as seen above. Each letter in a group will be treated as a separate option. The previous example is equivalent to:
cake my_command -c -n
Short options can also accept values:
cake my_command -c default
Positional arguments
If no positional arguments are defined, all of them will be parsed. If you define positional arguments any arguments greater than those defined will cause exceptions. Additionally you can declare arguments as optional, by setting the required param to false.
$parser->addArgument('model', ['required' => false]);
Providing Help text
By providing help text for your positional arguments and named arguments, the ConsoleOptionParser
can generate a help display for you. You can view the help for shells by using the --help
or -h
switch.
Table of Contents
Properties
- $_args : array<string|int, ConsoleInputArgument>
- Positional argument definitions.
- $_command : string
- Command name.
- $_description : string
- Description text - displays before options when help is generated
- $_epilog : string
- Epilog text - displays after options when help is generated
- $_options : array<string, ConsoleInputOption>
- Option definitions.
- $_shortOptions : array<string, string>
- Map of short -> long options, generated when using addOption()
- $_subcommands : array<string, ConsoleInputSubcommand>
- Subcommands for this Shell.
- $_subcommandSort : bool
- Subcommand sorting option
- $_tokens : array<string|int, mixed>
- Array of args (argv).
- $rootName : string
- Root alias used in help output
Methods
- __construct() : mixed
- Construct an OptionParser so you can define its behavior
- addArgument() : $this
- Add a positional argument to the option parser.
- addArguments() : $this
- Add multiple arguments at once. Take an array of argument definitions.
- addOption() : $this
- Add an option to the option parser. Options allow you to define optional or required parameters for your console application. Options are defined by the parameters they use.
- addOptions() : $this
- Add multiple options at once. Takes an array of option definitions.
- addSubcommand() : $this
- Append a subcommand to the subcommand list.
- addSubcommands() : $this
- Add multiple subcommands at once.
- argumentNames() : array<string|int, string>
- Get the list of argument names.
- arguments() : array<string|int, ConsoleInputArgument>
- Gets the arguments defined in the parser.
- buildFromArray() : static
- Build a parser from an array. Uses an array like
- create() : static
- Static factory method for creating new OptionParsers so you can chain methods off of them.
- enableSubcommandSort() : $this
- Enables sorting of subcommands
- getCommand() : string
- Gets the command name for shell/task.
- getDescription() : string
- Gets the description text for shell/task.
- getEpilog() : string
- Gets the epilog.
- help() : string
- Gets formatted help for this parser object.
- isSubcommandSortEnabled() : bool
- Checks whether sorting is enabled for subcommands.
- merge() : $this
- Get or set the command name for shell/task.
- options() : array<string, ConsoleInputOption>
- Get the defined options in the parser.
- parse() : array<string|int, mixed>
- Parse the argv array into a set of params and args. If $command is not null and $command is equal to a subcommand that has a parser, that parser will be used to parse the $argv
- removeOption() : $this
- Remove an option from the option parser.
- removeSubcommand() : $this
- Remove a subcommand from the option parser.
- setCommand() : $this
- Sets the command name for shell/task.
- setDescription() : $this
- Sets the description text for shell/task.
- setEpilog() : $this
- Sets an epilog to the parser. The epilog is added to the end of the options and arguments listing when help is generated.
- setRootName() : $this
- Set the root name used in the HelpFormatter
- subcommands() : array<string, ConsoleInputSubcommand>
- Get the array of defined subcommands
- toArray() : array<string, mixed>
- Returns an array representation of this parser.
- _nextToken() : string
- Find the next token in the argv set.
- _optionExists() : bool
- Check to see if $name has an option (short/long) defined for it.
- _parseArg() : array<string|int, string>
- Parse an argument, and ensure that the argument doesn't exceed the number of arguments and that the argument is a valid choice.
- _parseLongOption() : array<string|int, mixed>
- Parse the value for a long option out of $this->_tokens. Will handle options with an `=` in them.
- _parseOption() : array<string, mixed>
- Parse an option by its name index.
- _parseShortOption() : array<string, mixed>
- Parse the value for a short option out of $this->_tokens If the $option is a combination of multiple shortcuts like -otf they will be shifted onto the token stack and parsed individually.
Properties
$_args
Positional argument definitions.
protected
array<string|int, ConsoleInputArgument>
$_args
= []
Tags
$_command
Command name.
protected
string
$_command
= ''
$_description
Description text - displays before options when help is generated
protected
string
$_description
= ''
Tags
$_epilog
Epilog text - displays after options when help is generated
protected
string
$_epilog
= ''
Tags
$_options
Option definitions.
protected
array<string, ConsoleInputOption>
$_options
= []
Tags
$_shortOptions
Map of short -> long options, generated when using addOption()
protected
array<string, string>
$_shortOptions
= []
$_subcommands
Subcommands for this Shell.
protected
array<string, ConsoleInputSubcommand>
$_subcommands
= []
Tags
$_subcommandSort
Subcommand sorting option
protected
bool
$_subcommandSort
= true
$_tokens
Array of args (argv).
protected
array<string|int, mixed>
$_tokens
= []
$rootName
Root alias used in help output
protected
string
$rootName
= 'cake'
Tags
Methods
__construct()
Construct an OptionParser so you can define its behavior
public
__construct([string $command = '' ][, bool $defaultOptions = true ]) : mixed
Parameters
- $command : string = ''
-
The command name this parser is for. The command name is used for generating help.
- $defaultOptions : bool = true
-
Whether you want the verbose and quiet options set. Setting this to false will prevent the addition of
--verbose
&--quiet
options.
addArgument()
Add a positional argument to the option parser.
public
addArgument(ConsoleInputArgument|string $name[, array<string, mixed> $params = [] ]) : $this
Params
-
help
The help text to display for this argument. -
required
Whether this parameter is required. -
index
The index for the arg, if left undefined the argument will be put onto the end of the arguments. If you define the same index twice the first option will be overwritten. -
choices
A list of valid choices for this argument. If left empty all values are valid.. An exception will be raised when parse() encounters an invalid value.
Parameters
- $name : ConsoleInputArgument|string
-
The name of the argument. Will also accept an instance of ConsoleInputArgument.
- $params : array<string, mixed> = []
-
Parameters for the argument, see above.
Return values
$thisaddArguments()
Add multiple arguments at once. Take an array of argument definitions.
public
addArguments(array<string|int, mixed> $args) : $this
The keys are used as the argument names, and the values as params for the argument.
Parameters
- $args : array<string|int, mixed>
-
Array of arguments to add.
Tags
Return values
$thisaddOption()
Add an option to the option parser. Options allow you to define optional or required parameters for your console application. Options are defined by the parameters they use.
public
addOption(ConsoleInputOption|string $name[, array<string, mixed> $options = [] ]) : $this
Options
-
short
- The single letter variant for this option, leave undefined for none. -
help
- Help text for this option. Used when generating help for the option. -
default
- The default value for this option. Defaults are added into the parsed params when the attached option is not provided or has no value. Using default and boolean together will not work. are added into the parsed parameters when the option is undefined. Defaults to null. -
boolean
- The option uses no value, it's just a boolean switch. Defaults to false. If an option is defined as boolean, it will always be added to the parsed params. If no present it will be false, if present it will be true. -
multiple
- The option can be provided multiple times. The parsed option will be an array of values when this option is enabled. -
choices
A list of valid choices for this option. If left empty all values are valid.. An exception will be raised when parse() encounters an invalid value.
Parameters
- $name : ConsoleInputOption|string
-
The long name you want to the value to be parsed out as when options are parsed. Will also accept an instance of ConsoleInputOption.
- $options : array<string, mixed> = []
-
An array of parameters that define the behavior of the option
Return values
$thisaddOptions()
Add multiple options at once. Takes an array of option definitions.
public
addOptions(array<string, mixed> $options) : $this
The keys are used as option names, and the values as params for the option.
Parameters
- $options : array<string, mixed>
-
Array of options to add.
Tags
Return values
$thisaddSubcommand()
Append a subcommand to the subcommand list.
public
addSubcommand(ConsoleInputSubcommand|string $name[, array<string, mixed> $options = [] ]) : $this
Subcommands are usually methods on your Shell, but can also be used to document Tasks.
Options
-
help
- Help text for the subcommand. -
parser
- A ConsoleOptionParser for the subcommand. This allows you to create method specific option parsers. When help is generated for a subcommand, if a parser is present it will be used.
Parameters
- $name : ConsoleInputSubcommand|string
-
Name of the subcommand. Will also accept an instance of ConsoleInputSubcommand.
- $options : array<string, mixed> = []
-
Array of params, see above.
Return values
$thisaddSubcommands()
Add multiple subcommands at once.
public
addSubcommands(array<string, mixed> $commands) : $this
Parameters
- $commands : array<string, mixed>
-
Array of subcommands.
Return values
$thisargumentNames()
Get the list of argument names.
public
argumentNames() : array<string|int, string>
Return values
array<string|int, string>arguments()
Gets the arguments defined in the parser.
public
arguments() : array<string|int, ConsoleInputArgument>
Return values
array<string|int, ConsoleInputArgument>buildFromArray()
Build a parser from an array. Uses an array like
public
static buildFromArray(array<string, mixed> $spec[, bool $defaultOptions = true ]) : static
$spec = [
'description' => 'text',
'epilog' => 'text',
'arguments' => [
// list of arguments compatible with addArguments.
],
'options' => [
// list of options compatible with addOptions
],
'subcommands' => [
// list of subcommands to add.
]
];
Parameters
- $spec : array<string, mixed>
-
The spec to build the OptionParser with.
- $defaultOptions : bool = true
-
Whether you want the verbose and quiet options set.
Return values
staticcreate()
Static factory method for creating new OptionParsers so you can chain methods off of them.
public
static create(string $command[, bool $defaultOptions = true ]) : static
Parameters
- $command : string
-
The command name this parser is for. The command name is used for generating help.
- $defaultOptions : bool = true
-
Whether you want the verbose and quiet options set.
Return values
staticenableSubcommandSort()
Enables sorting of subcommands
public
enableSubcommandSort([bool $value = true ]) : $this
Parameters
- $value : bool = true
-
Whether to sort subcommands
Return values
$thisgetCommand()
Gets the command name for shell/task.
public
getCommand() : string
Return values
string —The value of the command.
getDescription()
Gets the description text for shell/task.
public
getDescription() : string
Return values
string —The value of the description
getEpilog()
Gets the epilog.
public
getEpilog() : string
Return values
string —The value of the epilog.
help()
Gets formatted help for this parser object.
public
help([string|null $subcommand = null ][, string $format = 'text' ][, int $width = 72 ]) : string
Generates help text based on the description, options, arguments, subcommands and epilog in the parser.
Parameters
- $subcommand : string|null = null
-
If present and a valid subcommand that has a linked parser. That subcommands help will be shown instead.
- $format : string = 'text'
-
Define the output format, can be text or XML
- $width : int = 72
-
The width to format user content to. Defaults to 72
Return values
string —Generated help.
isSubcommandSortEnabled()
Checks whether sorting is enabled for subcommands.
public
isSubcommandSortEnabled() : bool
Return values
boolmerge()
Get or set the command name for shell/task.
public
merge(ConsoleOptionParser|array<string|int, mixed> $spec) : $this
Parameters
- $spec : ConsoleOptionParser|array<string|int, mixed>
-
ConsoleOptionParser or spec to merge with.
Return values
$thisoptions()
Get the defined options in the parser.
public
options() : array<string, ConsoleInputOption>
Return values
array<string, ConsoleInputOption>parse()
Parse the argv array into a set of params and args. If $command is not null and $command is equal to a subcommand that has a parser, that parser will be used to parse the $argv
public
parse(array<string|int, mixed> $argv[, ConsoleIo|null $io = null ]) : array<string|int, mixed>
Parameters
- $argv : array<string|int, mixed>
-
Array of args (argv) to parse.
- $io : ConsoleIo|null = null
-
A ConsoleIo instance or null. If null prompt options will error.
Tags
Return values
array<string|int, mixed> —[$params, $args]
removeOption()
Remove an option from the option parser.
public
removeOption(string $name) : $this
Parameters
- $name : string
-
The option name to remove.
Return values
$thisremoveSubcommand()
Remove a subcommand from the option parser.
public
removeSubcommand(string $name) : $this
Parameters
- $name : string
-
The subcommand name to remove.
Return values
$thissetCommand()
Sets the command name for shell/task.
public
setCommand(string $text) : $this
Parameters
- $text : string
-
The text to set.
Return values
$thissetDescription()
Sets the description text for shell/task.
public
setDescription(array<string|int, string>|string $text) : $this
Parameters
- $text : array<string|int, string>|string
-
The text to set. If an array the text will be imploded with "\n".
Return values
$thissetEpilog()
Sets an epilog to the parser. The epilog is added to the end of the options and arguments listing when help is generated.
public
setEpilog(array<string|int, string>|string $text) : $this
Parameters
- $text : array<string|int, string>|string
-
The text to set. If an array the text will be imploded with "\n".
Return values
$thissetRootName()
Set the root name used in the HelpFormatter
public
setRootName(string $name) : $this
Parameters
- $name : string
-
The root command name
Return values
$thissubcommands()
Get the array of defined subcommands
public
subcommands() : array<string, ConsoleInputSubcommand>
Return values
array<string, ConsoleInputSubcommand>toArray()
Returns an array representation of this parser.
public
toArray() : array<string, mixed>
Return values
array<string, mixed>_nextToken()
Find the next token in the argv set.
protected
_nextToken() : string
Return values
string —next token or ''
_optionExists()
Check to see if $name has an option (short/long) defined for it.
protected
_optionExists(string $name) : bool
Parameters
- $name : string
-
The name of the option.
Return values
bool_parseArg()
Parse an argument, and ensure that the argument doesn't exceed the number of arguments and that the argument is a valid choice.
protected
_parseArg(string $argument, array<string|int, mixed> $args) : array<string|int, string>
Parameters
- $argument : string
-
The argument to append
- $args : array<string|int, mixed>
-
The array of parsed args to append to.
Tags
Return values
array<string|int, string> —Args
_parseLongOption()
Parse the value for a long option out of $this->_tokens. Will handle options with an `=` in them.
protected
_parseLongOption(string $option, array<string, mixed> $params) : array<string|int, mixed>
Parameters
- $option : string
-
The option to parse.
- $params : array<string, mixed>
-
The params to append the parsed value into
Return values
array<string|int, mixed> —Params with $option added in.
_parseOption()
Parse an option by its name index.
protected
_parseOption(string $name, array<string, mixed> $params) : array<string, mixed>
Parameters
- $name : string
-
The name to parse.
- $params : array<string, mixed>
-
The params to append the parsed value into
Tags
Return values
array<string, mixed> —Params with $option added in.
_parseShortOption()
Parse the value for a short option out of $this->_tokens If the $option is a combination of multiple shortcuts like -otf they will be shifted onto the token stack and parsed individually.
protected
_parseShortOption(string $option, array<string, mixed> $params) : array<string, mixed>
Parameters
- $option : string
-
The option to parse.
- $params : array<string, mixed>
-
The params to append the parsed value into
Tags
Return values
array<string, mixed> —Params with $option added in.