Making ConsoleOptionParser not default options to true. Having them this way made it pretty difficult to write simple conditions in shells, as options would always be truthy.

This commit is contained in:
mark_story 2010-10-16 00:39:22 -04:00
parent 02f42f3454
commit ced7243f95
2 changed files with 10 additions and 7 deletions

View file

@ -252,7 +252,7 @@ class ConsoleOptionParser {
* - `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.
* are added into the parsed parameters when the option is undefined. Defaults to null.
* - `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
* it will be false, if present it will be true.
@ -268,7 +268,7 @@ class ConsoleOptionParser {
'name' => $name,
'short' => null,
'help' => '',
'default' => true,
'default' => null,
'boolean' => false,
'choices' => array()
);
@ -609,10 +609,13 @@ class ConsoleOptionParser {
throw new InvalidArgumentException(sprintf(__('Unknown option `%s`'), $name));
}
$option = $this->_options[$name];
$isBoolean = $option->isBoolean();
$nextValue = $this->_nextToken();
if (!$option->isBoolean() && !empty($nextValue) && $nextValue{0} != '-') {
if (!$isBoolean && !empty($nextValue) && $nextValue{0} != '-') {
array_shift($this->_tokens);
$value = $nextValue;
} elseif ($isBoolean) {
$value = true;
} else {
$value = $option->defaultValue();
}

View file

@ -155,9 +155,9 @@ class ConsoleOptionParserTest extends CakeTestCase {
*/
function testAddOptionMultipleShort() {
$parser = new ConsoleOptionParser('test', false);
$parser->addOption('test', array('short' => 't'))
->addOption('file', array('short' => 'f'))
->addOption('output', array('short' => 'o'));
$parser->addOption('test', array('short' => 't', 'boolean' => true))
->addOption('file', array('short' => 'f', 'boolean' => true))
->addOption('output', array('short' => 'o', 'boolean' => true));
$result = $parser->parse(array('-o', '-t', '-f'));
$expected = array('file' => true, 'test' => true, 'output' => true, 'help' => false);
@ -176,7 +176,7 @@ class ConsoleOptionParserTest extends CakeTestCase {
$parser = new ConsoleOptionParser('test', false);
$parser->addOption('test')
->addOption('connection')
->addOption('table', array('short' => 't'));
->addOption('table', array('short' => 't', 'default' => true));
$result = $parser->parse(array('--test', 'value', '-t', '--connection', 'postgres'));
$expected = array('test' => 'value', 'table' => true, 'connection' => 'postgres', 'help' => false);