Skip to content

Commit

Permalink
Adding support for boolean options.
Browse files Browse the repository at this point in the history
  • Loading branch information
markstory committed Oct 14, 2010
1 parent 3e402e2 commit 505e59a
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
7 changes: 5 additions & 2 deletions cake/console/console_option_parser.php
Expand Up @@ -117,6 +117,7 @@ public function epilog($text = null) {
* - `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. If not defined the default will be true.
* - `boolean` - The option uses no value, its just a boolean switch. Defaults to false.
*
* @param string $name The long name you want to the value to be parsed out as when options are parsed.
* @param array $params An array of parameters that define the behavior of the option
Expand All @@ -127,7 +128,8 @@ public function addOption($name, $params = array()) {
'name' => $name,
'short' => null,
'help' => '',
'default' => true
'default' => true,
'boolean' => false
);
$options = array_merge($defaults, $params);
$this->_options[$name] = $options;
Expand Down Expand Up @@ -245,7 +247,8 @@ protected function _parseShortOption($option, $params) {
protected function _parseOptionName($name, $params) {
$definition = $this->_options[$name];
$nextValue = $this->_nextToken();
if (!empty($nextValue) && $nextValue{0} != '-') {
if (!$definition['boolean'] && !empty($nextValue) && $nextValue{0} != '-') {
array_shift($this->_tokens);
$value = $nextValue;
} else {
$value = $definition['default'];
Expand Down
17 changes: 17 additions & 0 deletions cake/tests/cases/console/console_option_parser.test.php
Expand Up @@ -150,6 +150,22 @@ function testMultipleOptions() {
$this->assertEquals($expected, $result[0], 'multiple options did not parse');
}

/**
* test that boolean options work
*
* @return void
*/
function testOptionWithBooleanParam() {
$parser = new ConsoleOptionParser();
$parser->addOption('no-commit', array('boolean' => true))
->addOption('table', array('short' => 't'));

$result = $parser->parse(array('--table', 'posts', '--no-commit', 'arg1', 'arg2'));
$expected = array(array('table' => 'posts', 'no-commit' => true), array('arg1', 'arg2'));
$this->assertEquals($expected, $result, 'Boolean option did not parse correctly.');

}

/**
* test positional argument parsing.
*
Expand Down Expand Up @@ -189,6 +205,7 @@ function testParseArgument() {
$expected = array('one', 'two');
$result = $parser->parse($expected);
$this->assertEquals($expected, $result[1], 'Arguments are not as expected');

$result = $parser->parse(array('one', 'two', 'three'));
}
}

0 comments on commit 505e59a

Please sign in to comment.