From f5ad54e97e564ba97383e57d8018ad863ab322d5 Mon Sep 17 00:00:00 2001 From: mark_story Date: Sat, 9 Oct 2010 10:41:11 -0400 Subject: [PATCH] Adding required argument checking. --- cake/console/console_option_parser.php | 37 +++++++++++++++++-- .../console/console_option_parser.test.php | 16 +++++++- 2 files changed, 49 insertions(+), 4 deletions(-) diff --git a/cake/console/console_option_parser.php b/cake/console/console_option_parser.php index ffb6c23ed86..5c4bd1904b5 100644 --- a/cake/console/console_option_parser.php +++ b/cake/console/console_option_parser.php @@ -28,12 +28,36 @@ */ class ConsoleOptionParser { +/** + * Description text - displays before options when help is generated + * + * @see ConsoleOptionParser::description() + * @var string + */ protected $_description = null; - + +/** + * Epilog text - displays after options when help is generated + * + * @see ConsoleOptionParser::epilog() + * @var string + */ protected $_epilog = null; - + +/** + * Option definitions. + * + * @see ConsoleOptionParser::addOption() + * @var array + */ protected $_options = array(); - + +/** + * Positional argument definitions. + * + * @see ConsoleOptionParser::addArgument() + * @var array + */ protected $_args = array(); /** @@ -195,6 +219,13 @@ public function parse($argv) { $args = $this->_parseArg($token, $args); } } + foreach ($this->_args as $i => $arg) { + if ($arg['required'] && !isset($args[$i])) { + throw new RuntimeException( + sprintf(__('Missing required arguments. %s is required.'), $arg['name']) + ); + } + } return array($params, $args); } diff --git a/cake/tests/cases/console/console_option_parser.test.php b/cake/tests/cases/console/console_option_parser.test.php index 63b22d5ad66..2b7863483e4 100644 --- a/cake/tests/cases/console/console_option_parser.test.php +++ b/cake/tests/cases/console/console_option_parser.test.php @@ -197,7 +197,7 @@ function testPositionalArgOverwrite() { * @expectedException InvalidArgumentException * @return void */ - function testParseArgument() { + function testParseArgumentTooMany() { $parser = new ConsoleOptionParser(); $parser->addArgument('name', array('help' => 'An argument')) ->addArgument('other'); @@ -208,4 +208,18 @@ function testParseArgument() { $result = $parser->parse(array('one', 'two', 'three')); } + +/** + * test that when there are not enough arguments an exception is raised + * + * @expectedException RuntimeException + * @return void + */ + function testPositionalArgNotEnough() { + $parser = new ConsoleOptionParser(); + $parser->addArgument('name', array('required' => true)) + ->addArgument('other', array('required' => true)); + + $parser->parse(array('one')); + } } \ No newline at end of file