Adding default values into the parsed output.

This makes it so options with default values are always part of the parsed options regardless of whether or not they were included.  This will allow shells to include less logic checking for existence of parameters.
This commit is contained in:
mark_story 2010-10-11 23:12:38 -04:00
parent 3585620470
commit b328276289
2 changed files with 17 additions and 3 deletions

View file

@ -130,10 +130,12 @@ class ConsoleOptionParser {
if ($defaultOptions) {
$this->addOption('verbose', array(
'short' => 'v',
'help' => __('Enable verbose output.')
'help' => __('Enable verbose output.'),
'boolean' => true
))->addOption('quiet', array(
'short' => 'q',
'help' => __('Enable quiet output.')
'help' => __('Enable quiet output.'),
'boolean' => true
));
}
}
@ -249,7 +251,7 @@ class ConsoleOptionParser {
* - `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. Using default and boolean together will not work.
* 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.
* - `boolean` - The option uses no value, its 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
@ -442,6 +444,11 @@ class ConsoleOptionParser {
);
}
}
foreach ($this->_options as $option) {
if ($option->defaultValue() !== null && !isset($params[$option->name()]) && !$option->isBoolean()) {
$params[$option->name()] = $option->defaultValue();
}
}
return array($params, $args);
}

View file

@ -105,6 +105,13 @@ class ConsoleOptionParserTest extends CakeTestCase {
));
$result = $parser->parse(array('--test'));
$this->assertEquals(array('test' => 'default value'), $result[0], 'Default value did not parse out');
$parser = new ConsoleOptionParser();
$parser->addOption('test', array(
'default' => 'default value',
));
$result = $parser->parse(array());
$this->assertEquals(array('test' => 'default value'), $result[0], 'Default value did not parse out');
}
/**