diff --git a/examples/commands.php b/examples/commands.php new file mode 100644 index 0000000..5e36a3c --- /dev/null +++ b/examples/commands.php @@ -0,0 +1,21 @@ +add('help', function ($args, $shell) { + $shell->write("This could be usage help :)\n"); +}); +$commands->on('notfound', function ($command, $shell) { + $shell->write("Command not found: {$command}. Try help\n"); +}); + +$shell->on('prompt', function ($shell) { + $shell->setPrompt(date(">> ")); +}); +$shell->on('input', $commands); diff --git a/examples/timers.php b/examples/timers.php index 20fe78b..6f644c1 100644 --- a/examples/timers.php +++ b/examples/timers.php @@ -2,11 +2,11 @@ use React\EventLoop\Loop; -require_once __DIR__."/vendor/autoload.php"; +require_once __DIR__."/../vendor/autoload.php"; $shell = new NoccyLabs\React\Shell\Shell(); -$shell->on('prompt', function () use ($shell) { +$shell->on('prompt', function ($shell) { $shell->setPrompt(date("H:i:s> ")); }); $shell->on('input', function (array $input) use ($shell) { diff --git a/src/CommandHandler.php b/src/CommandHandler.php new file mode 100644 index 0000000..46e58c8 --- /dev/null +++ b/src/CommandHandler.php @@ -0,0 +1,39 @@ +commands[$command] = [ 'handler' => $handler, 'signature' => $signature ]; + return $this; + } + + public function __invoke(array $line, Shell $shell) + { + $this->execute($line, $shell); + } + + public function execute(array $line, Shell $shell) + { + $command = array_shift($line); + + if (!array_key_exists($command, $this->commands)) { + $this->emit("notfound", [ $command, $shell ]); + return; + } + + Loop::futureTick(fn() => call_user_func($this->commands[$command]['handler'], $line, $shell)); + + } +} \ No newline at end of file diff --git a/src/Shell.php b/src/Shell.php index 6e60eaf..849b95e 100644 --- a/src/Shell.php +++ b/src/Shell.php @@ -68,11 +68,16 @@ class Shell implements WritableStreamInterface, EventEmitterInterface exit(0); case "\n": - $buffer = str_getcsv($this->buffer, " "); + $buffer = str_getcsv(trim($this->buffer), " "); $this->buffer = ''; $this->cursorPos = 0; $this->scrollOffset = 0; - $this->emit('input', [ $buffer ]); + $this->ostream->write("\n"); + if ($buffer[0] !== NULL) { + $this->emit('input', [ $buffer, $this ]); + } else { + $this->redrawPrompt(); + } break; case "\x7F": // backspace @@ -156,7 +161,7 @@ class Shell implements WritableStreamInterface, EventEmitterInterface public function redrawPrompt(): void { - $prompt = $this->emit("prompt"); + $this->emit("prompt", [ $this ]); $this->termWidth = intval(exec("tput cols")); $this->isPrompting = true;