[Zend] Progressive CLI options fetching
Posted: Wed Jan 05, 2011 5:10 am
I'm building a CLI code generator framework - plugin based. In the "main loop" I fetch the --command option, create the appropriate "command" plugin object and initialize it. The plugin in turn, fetches the options needed by itself.
The problem is, the "main loop" doesn't know what options would be needed by the plugin, but still need to fetch the --command option. And when I try to fetch it Zend_Console_Getopt throws an exception - "Unrecognized XXX option" because the plugin to be loaded has not "described" its options yet.
So, I've made a quick and dirty solution:
And later I simply use:
Is there something I'm missing in Zend_Console_Getopt? Do I really need this hack?
The problem is, the "main loop" doesn't know what options would be needed by the plugin, but still need to fetch the --command option. And when I try to fetch it Zend_Console_Getopt throws an exception - "Unrecognized XXX option" because the plugin to be loaded has not "described" its options yet.
So, I've made a quick and dirty solution:
Code: Select all
<?php
class ZendEx_Console_Getopt extends \Zend_Console_Getopt
{
const CONFIG_PERMIT_UNKNOWN = 'permitUknown';
public function __construct($rules, $argv = null, $getoptConfig = array())
{
parent::__construct($rules, $argv, $getoptConfig);
$this->_options[CONFIG_PERMIT_UNKNOWN] = false;
}
public function resetParsing()
{
$this->_parsed = false;
}
protected function _parseSingleOption($flag, &$argv)
{
if ($this->_getoptConfig[self::CONFIG_IGNORECASE]) {
$flag = strtolower($flag);
}
if (!isset($this->_ruleMap[$flag])) {
/**
* @hack Do not die on unrecognized options
*/
if ($this->_getoptConfig[self::CONFIG_PERMIT_UNKNOWN])
return null;
require_once 'Zend/Console/Getopt/Exception.php';
throw new \Zend_Console_Getopt_Exception(
"Option \"$flag\" is not recognized.",
$this->getUsageMessage());
}
$realFlag = $this->_ruleMap[$flag];
switch ($this->_rules[$realFlag]['param']) {
case 'required':
if (count($argv) > 0) {
$param = array_shift($argv);
$this->_checkParameterType($realFlag, $param);
} else {
require_once 'Zend/Console/Getopt/Exception.php';
throw new \Zend_Console_Getopt_Exception(
"Option \"$flag\" requires a parameter.",
$this->getUsageMessage());
}
break;
case 'optional':
if (count($argv) > 0 && substr($argv[0], 0, 1) != '-') {
$param = array_shift($argv);
$this->_checkParameterType($realFlag, $param);
} else {
$param = true;
}
break;
default:
$param = true;
}
$this->_options[$realFlag] = $param;
}
}Code: Select all
$getopt->setOption(\CryoGen\ZendEx_Console_Getopt::CONFIG_PERMIT_UNKNOWN, true);