react-shell/src/CommandHandler.php

40 lines
947 B
PHP

<?php
namespace NoccyLabs\React\Shell;
use Evenement\EventEmitterInterface;
use Evenement\EventEmitterTrait;
use React\EventLoop\Loop;
class CommandHandler implements EventEmitterInterface
{
use EventEmitterTrait;
private array $commands = [];
public function add(string $command, callable $handler, array $signature=[]): self
{
$this->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("command", [ $command, $line, $shell ]);
return;
}
Loop::futureTick(fn() => call_user_func($this->commands[$command]['handler'], $line, $shell));
}
}