Skip to content

Commit

Permalink
Adding ability to define a subcommand parser as an array.
Browse files Browse the repository at this point in the history
This makes defining subcommands a bit easier as you don't have to build a pile of objects first.
  • Loading branch information
markstory committed Oct 14, 2010
1 parent 1fec75e commit 7a31eb4
Show file tree
Hide file tree
Showing 3 changed files with 67 additions and 0 deletions.
4 changes: 4 additions & 0 deletions cake/console/console_input_subcommand.php
Expand Up @@ -49,6 +49,10 @@ public function __construct($name, $help = '', $parser = null) {
$this->_help = $help;
$this->_parser = $parser;
}
if (is_array($this->_parser)) {
$this->_parser['command'] = $this->_name;
$this->_parser = ConsoleOptionParser::buildFromArray($this->_parser);
}
}

/**
Expand Down
31 changes: 31 additions & 0 deletions cake/console/console_option_parser.php
Expand Up @@ -136,6 +136,37 @@ public function __construct($command = null, $defaultOptions = true) {
}
}

/**
* Static factory method for creating new OptionParsers so you can chain methods off of them.
*
* @return ConsoleOptionParser
*/
public static function create($command, $defaultOptions = true) {
return new ConsoleOptionParser($command, $defaultOptions);
}

/**
* Build a parser from an array.
*
* @return ConsoleOptionParser
*/
public static function buildFromArray($spec) {
$parser = new ConsoleOptionParser($spec['command']);
if (!empty($spec['arguments'])) {
$parser->addArguments($spec['arguments']);
}
if (!empty($spec['options'])) {
$parser->addOptions($spec['options']);
}
if (!empty($spec['description'])) {
$parser->description($spec['description']);
}
if (!empty($spec['epilog'])) {
$parser->epilog($spec['epilog']);
}
return $parser;
}

/**
* Get or set the command name for shell/task
*
Expand Down
32 changes: 32 additions & 0 deletions cake/tests/cases/console/console_option_parser.test.php
Expand Up @@ -496,4 +496,36 @@ function testHelpSubcommandHelp() {
TEXT;
$this->assertEquals($expected, $result, 'Help is not correct.');
}

/**
* test building a parser from an array.
*
* @return void
*/
function testBuildFromArray() {
$spec = array(
'command' => 'test',
'arguments' => array(
'name' => array('help' => 'The name'),
'other' => array('help' => 'The other arg')
),
'options' => array(
'name' => array('help' => 'The name'),
'other' => array('help' => 'The other arg')
),
'description' => 'description text',
'epilog' => 'epilog text'
);
$parser = ConsoleOptionParser::buildFromArray($spec);

$this->assertEquals($spec['description'], $parser->description());
$this->assertEquals($spec['epilog'], $parser->epilog());

$options = $parser->options();
$this->assertTrue(isset($options['name']));
$this->assertTrue(isset($options['other']));

$args = $parser->arguments();
$this->assertEquals(2, count($args));
}
}

0 comments on commit 7a31eb4

Please sign in to comment.