diff --git a/lib/cli/Arguments.php b/lib/cli/Arguments.php index 0806dee..6108203 100644 --- a/lib/cli/Arguments.php +++ b/lib/cli/Arguments.php @@ -392,6 +392,8 @@ public function parse() { $this->_parsed = array(); $this->_lexer = new Lexer($this->_input); + $this->_applyDefaults(); + foreach ($this->_lexer as $argument) { if ($this->_parseFlag($argument)) { continue; @@ -408,6 +410,24 @@ public function parse() { } } + /** + * This applies the default values, if any, of all of the + * flags and options, so that if there is a default value + * it will be available. + */ + private function _applyDefaults() { + foreach($this->_flags as $flag => $settings) { + $this[$flag] = $settings['default']; + } + + foreach($this->_options as $option => $settings) { + // If the default is 0 we should still let it be set. + if (!empty($settings['default']) || $settings['default'] === 0) { + $this[$option] = $settings['default']; + } + } + } + private function _warn($message) { trigger_error('[' . __CLASS__ .'] ' . $message, E_USER_WARNING); } @@ -439,7 +459,7 @@ private function _parseOption($option) { if ($this->_lexer->end() || !$this->_lexer->peek->isValue) { $optionSettings = $this->getOption($option->key); - if (empty($optionSettings['default'])) { + if (empty($optionSettings['default']) && $optionSettings !== 0) { // Oops! Got no value and no default , throw a warning and continue. $this->_warn('no value given for ' . $option->raw); $this[$option->key] = null; @@ -466,4 +486,3 @@ private function _parseOption($option) { return true; } } - diff --git a/tests/test-arguments.php b/tests/test-arguments.php index c92d3fa..f828926 100644 --- a/tests/test-arguments.php +++ b/tests/test-arguments.php @@ -146,7 +146,7 @@ public function testAddOptions() } /** - * Data provider with valid fags and options + * Data provider with valid args and options * * @return array set of args and expected parsed values */ @@ -206,6 +206,16 @@ public function settingsWithMissingOptionsWithDefault() ); } + public function settingsWithNoOptionsWithDefault() + { + return array( + array( + array(), + array('flag1' => false, 'flag2' => false, 'option2' => 'some default value') + ) + ); + } + /** * Generic private testParse method. * @@ -221,7 +231,7 @@ private function _testParse($cliParams, $expectedValues) foreach ($expectedValues as $name => $value) { if ($args->isFlag($name)) { - $this->assertTrue($args[$name]); + $this->assertEquals($value, $args[$name]); } if ($args->isOption($name)) { @@ -262,4 +272,13 @@ public function testParseWithMissingOptionsWithDefault($cliParams, $expectedValu { $this->_testParse($cliParams, $expectedValues); } + + /** + * @param array $args arguments as they appear in the cli + * @param array $expectedValues expected values after parsing + * @dataProvider settingsWithNoOptionsWithDefault + */ + public function testParseWithNoOptionsWithDefault($cliParams, $expectedValues) { + $this->_testParse($cliParams, $expectedValues); + } }