Skip to content

Commit

Permalink
Adding required argument checking.
Browse files Browse the repository at this point in the history
  • Loading branch information
markstory committed Oct 14, 2010
1 parent 505e59a commit f5ad54e
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 4 deletions.
37 changes: 34 additions & 3 deletions cake/console/console_option_parser.php
Expand Up @@ -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();

/**
Expand Down Expand Up @@ -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);
}

Expand Down
16 changes: 15 additions & 1 deletion cake/tests/cases/console/console_option_parser.test.php
Expand Up @@ -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');
Expand All @@ -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'));
}
}

0 comments on commit f5ad54e

Please sign in to comment.