Added an execute() method to context to catch unhandled commands

This commit is contained in:
Christopher Vagnetoft 2016-11-19 14:18:53 +01:00
parent 7bfd8453e7
commit 43a6475192
3 changed files with 43 additions and 0 deletions

20
examples/catchall.php Normal file
View File

@ -0,0 +1,20 @@
<?php
require_once __DIR__."/../vendor/autoload.php";
use NoccyLabs\Shell\Shell;
use NoccyLabs\Shell\Context;
class CatchAllContext extends Context
{
public function execute($cmd, ...$arg)
{
printf("Executing: %s %s\n", $cmd, join(" ",$arg));
return true;
}
}
$myShell = new Shell();
$myShell->setPrompt("test>");
$myShell->pushContext(new CatchAllContext());
$myShell->run();

View File

@ -146,6 +146,23 @@ class Context
return array_key_exists('global', $info); return array_key_exists('global', $info);
} }
/**
* Catch-all handler for commands not defined in context, globally or builtin.
* Override this function and return true if the command is handled ok.
*
* @param string $command The command to execute
* @param string[] $args The arguments to the command
* @return bool True if the command was handled
*/
public function execute($command, ...$args)
{
return false;
}
/**
* Get the name of the context
*
*/
public function getName() public function getName()
{ {
return $this->name; return $this->name;

View File

@ -223,6 +223,12 @@ class Shell
} }
return; return;
} }
// Call 'execute' on the current context
if ($this->context->execute($command, ...$args)) {
return;
}
// Throw error if the command could not be found // Throw error if the command could not be found
throw new Exception\BadCommandException("Command {$command} not found"); throw new Exception\BadCommandException("Command {$command} not found");
} }