From 43a6475192a403ea945c86d7ce27536ef8412cf9 Mon Sep 17 00:00:00 2001 From: Christopher Vagnetoft Date: Sat, 19 Nov 2016 14:18:53 +0100 Subject: [PATCH] Added an execute() method to context to catch unhandled commands --- examples/catchall.php | 20 ++++++++++++++++++++ lib/Context.php | 17 +++++++++++++++++ lib/Shell.php | 6 ++++++ 3 files changed, 43 insertions(+) create mode 100644 examples/catchall.php diff --git a/examples/catchall.php b/examples/catchall.php new file mode 100644 index 0000000..7c503af --- /dev/null +++ b/examples/catchall.php @@ -0,0 +1,20 @@ +setPrompt("test>"); +$myShell->pushContext(new CatchAllContext()); +$myShell->run(); diff --git a/lib/Context.php b/lib/Context.php index 0b1da8b..c8f36e9 100644 --- a/lib/Context.php +++ b/lib/Context.php @@ -146,6 +146,23 @@ class Context 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() { return $this->name; diff --git a/lib/Shell.php b/lib/Shell.php index da24fbb..8f067ad 100644 --- a/lib/Shell.php +++ b/lib/Shell.php @@ -223,6 +223,12 @@ class Shell } return; } + + // Call 'execute' on the current context + if ($this->context->execute($command, ...$args)) { + return; + } + // Throw error if the command could not be found throw new Exception\BadCommandException("Command {$command} not found"); }