Improved context commands
This commit is contained in:
@ -8,6 +8,8 @@ class Context
|
||||
|
||||
protected $commands = [];
|
||||
|
||||
protected $commandInfo = [];
|
||||
|
||||
protected $data = [];
|
||||
|
||||
|
||||
@ -21,11 +23,42 @@ class Context
|
||||
protected function configure()
|
||||
{
|
||||
// Override this to do setup stuff
|
||||
$this->findCommands();
|
||||
}
|
||||
|
||||
public function addCommand($command, callable $handler)
|
||||
protected function findCommands()
|
||||
{
|
||||
$refl = new \ReflectionClass(get_called_class());
|
||||
foreach ($refl->getMethods() as $method) {
|
||||
$docblock = $method->getDocComment();
|
||||
$lines = array_map(function ($line) {
|
||||
return trim($line, "*/ \t");
|
||||
}, explode("\n", $docblock));
|
||||
$info = [];
|
||||
foreach ($lines as $line) {
|
||||
if (preg_match("/^@(command|help|args) (.+?)$/", $line, $match)) {
|
||||
list($void,$key,$value) = $match;
|
||||
$info[$key] = $value;
|
||||
}
|
||||
if (count($info)>0) {
|
||||
$this->addCommand($method->getName(), [$this, $method->getName()], $info);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function addCommand($command, callable $handler, array $info=[])
|
||||
{
|
||||
$this->commands[$command] = $handler;
|
||||
$this->commandInfo[$command] = $info;
|
||||
}
|
||||
|
||||
public function setCommandHelp($command, $help)
|
||||
{
|
||||
if (!array_key_exists($command, $this->commandInfo)) {
|
||||
return;
|
||||
}
|
||||
$this->commandInfo[$command]['help'] = $help;
|
||||
}
|
||||
|
||||
public function addCommands(array $commands)
|
||||
@ -50,6 +83,18 @@ class Context
|
||||
return $this->commands[$command];
|
||||
}
|
||||
|
||||
public function getCommandHelp()
|
||||
{
|
||||
$ret = [];
|
||||
foreach ($this->commands as $command=>$handler) {
|
||||
$info = $this->commandInfo[$command];
|
||||
$args = array_key_exists("args",$info)?$info['args']:"";
|
||||
$help = array_key_exists("help",$info)?$info['help']:"";
|
||||
$ret[trim("{$command} {$args}")] = $help;
|
||||
}
|
||||
return $ret;
|
||||
}
|
||||
|
||||
public function getName()
|
||||
{
|
||||
return $this->name;
|
||||
|
Reference in New Issue
Block a user