From 75c624520df341816e8cacd1f7dd030b5486502a Mon Sep 17 00:00:00 2001 From: Christopher Vagnetoft Date: Sun, 29 Jan 2017 20:27:17 +0100 Subject: [PATCH] Updated examples, added onEnter method to contexts --- examples/commandevents.php | 6 ++--- examples/contexts.php | 51 ++++++++++++++++++++++++++++---------- lib/Context.php | 5 ++++ lib/Shell.php | 1 + 4 files changed, 47 insertions(+), 16 deletions(-) diff --git a/examples/commandevents.php b/examples/commandevents.php index e45a7bf..d904729 100644 --- a/examples/commandevents.php +++ b/examples/commandevents.php @@ -36,9 +36,9 @@ $myShell->setPrompt("test>"); // Create an anonymous context and add a command $ctx = $myShell->createContext("root"); -$ctx->addCommand("hello", function () { - echo "Hello World!\n"; -}); +$ctx->addCommand("hello", function ($who="World") { + echo "Hello {$who}!\n"; +}, [ "help"=>"Say hello", "args"=>"who" ]); // Run the shell $myShell->run(); diff --git a/examples/contexts.php b/examples/contexts.php index 424567c..82226f8 100644 --- a/examples/contexts.php +++ b/examples/contexts.php @@ -6,21 +6,46 @@ use NoccyLabs\Shell\Shell; use NoccyLabs\Shell\Context; $shell = new Shell(); -$shell->addListener("prompt", function ($event, $shell) { - $name = $shell->getContextPath(); - $shell->setPrompt("shell{$name}> "); +$shell->addListener(Shell::EVT_UPDATE_PROMPT, function ($event) { + $name = $event->shell->getContextPath(); + $event->shell->setPrompt("shell{$name}> "); }); -$root = new Context(); -$root->addCommand("test", function () { - echo "It works!\n"; -}); -$root->addCommand("context", function ($name) { - $context = new Context($name); - $context->name = $name; - return $context; -}); -$shell->pushContext($root); +class MyContext extends Context +{ + public function __construct() + { + // Remember to call the parent constructor if you want to use + // the doccomment syntax to mark commands, as demonstrated + // at the end of this class for the bar command. + parent::__construct(); + $this->addCommand("foo",[$this,"foo"],[ + 'help' => "Foo command" + ]); + } + + public function onEnter() + { + echo "Entering context!\n"; + } + + public function foo() + { + echo "Foo!\n"; + } + + /** + * @command bar + * @args + * @help Bar command + */ + public function bar() + { + echo "Bar!\n"; + } +} + +$shell->pushContext(new MyContext()); $shell->run(); diff --git a/lib/Context.php b/lib/Context.php index c8f36e9..c5f029c 100644 --- a/lib/Context.php +++ b/lib/Context.php @@ -66,6 +66,11 @@ class Context $this->findCommands(); } + public function onEnter() + { + } + + protected function findCommands() { $refl = new \ReflectionClass(get_called_class()); diff --git a/lib/Shell.php b/lib/Shell.php index 768730c..7875d93 100644 --- a/lib/Shell.php +++ b/lib/Shell.php @@ -113,6 +113,7 @@ class Shell } $context->setShell($this); $this->context = $context; + $context->onEnter(); $this->dispatchEvent(self::EVT_CONTEXT_CHANGED); }