Adding the ability for parse() to use a subcommand parser.

Adding text on how to get help on subcommands.
This commit is contained in:
mark_story 2010-10-11 01:32:09 -04:00
parent 1cf2613a8d
commit 970a6c8d79
2 changed files with 44 additions and 3 deletions

View file

@ -372,14 +372,20 @@ class ConsoleOptionParser {
}
/**
* Parse the argv array into a set of params and args.
* Parse the argv array into a set of params and args. If $command is not null
* and $command is equal to a subcommand that has a parser, that parser will be used
* to parse the $argv
*
* @param array $argv Array of args (argv) to parse
* @param array $argv Array of args (argv) to parse.
* @param string $command The subcommand to use for parsing.
* @return Array array($params, $args)
* @throws InvalidArgumentException When an invalid parameter is encountered.
* RuntimeException when required arguments are not supplied.
*/
public function parse($argv) {
public function parse($argv, $command = null) {
if (isset($this->_subcommands[$command]) && $this->_subcommands[$command]->parser()) {
return $this->_subcommands[$command]->parser()->parse($argv);
}
$params = $args = array();
$this->_tokens = $argv;
while ($token = array_shift($this->_tokens)) {
@ -435,6 +441,11 @@ class ConsoleOptionParser {
$out[] = $command->help($max);
}
$out[] = '';
$out[] = sprintf(
__('To see help on a subcommand use <info>`cake %s [subcommand] --help`</info>'),
$this->command()
);
$out[] = '';
}
if (!empty($this->_options)) {

View file

@ -464,6 +464,8 @@ cake mycommand [subcommand] [-h] [--test]
method This is another command
To see help on a subcommand use <info>`cake mycommand [subcommand] --help`</info>
<info>Options:</info>
--help, -h Display this help.
@ -534,4 +536,32 @@ TEXT;
$args = $parser->arguments();
$this->assertEquals(2, count($args));
}
/**
* test that parse() takes a subcommand argument, and that the subcommand parser
* is used.
*
* @return void
*/
function testParsingWithSubParser() {
$parser = new ConsoleOptionParser();
$parser->addOption('primary')
->addArgument('one', array('required' => true, 'choices' => array('a', 'b')))
->addArgument('two', array('required' => true))
->addSubcommand('sub', array(
'parser' => array(
'options' => array(
'secondary' => array('boolean' => true),
'fourth' => array('help' => 'fourth option')
),
'arguments' => array(
'sub_arg' => array('choices' => array('c', 'd'))
)
)
));
$result = $parser->parse(array('--secondary', '--fourth', '4', 'c'), 'sub');
$expected = array(array('secondary' => true, 'fourth' => '4'), array('c'));
$this->assertEquals($expected, $result, 'Sub parser did not parse request.');
}
}