php-shell/lib/Shell.php

88 lines
1.9 KiB
PHP

<?php
namespace NoccyLabs\Shell;
use NoccyLabs\Shell\LineRead;
abstract class Shell
{
public function __construct(array $config=[])
{
$this->configure($config);
}
abstract protected function configure(array $config);
public function addCommand($command, callable $handler)
{
$this->commands[$command] = $handler;
}
public function execute($command)
{
$buffer = str_getcsv($command, " ", "\"", "\\");
if (count($buffer)>0) {
$this->executeBuffer($buffer);
}
}
protected function executeBuffer(array $buffer)
{
$commandName = array_shift($buffer);
if (array_key_exists($commandName, $this->commands)) {
$command = $this->commands[$commandName];
call_user_func_array($command,$buffer);
return;
}
$this->writeln("Bad command: ".$commandName);
}
public function writeln($output)
{
echo "\r\e[K\e[0m".$output."\n";
}
protected function onUpdate()
{
}
public function run(callable $updateFunc=null)
{
$lineRead = new LineRead();
$this->running = true;
do {
$buffer = $lineRead->update();
ob_start();
if (is_callable($updateFunc)) {
call_user_func($updateFunc);
}
$this->onUpdate();
$buf = ob_get_contents();
ob_end_clean();
if ($buf) {
$lineRead->erase();
echo rtrim($buf)."\n";
$lineRead->redraw();
}
//$buffer = readline($this->getPrompt());
if ($buffer === null) {
usleep(10000);
continue;
} else {
$this->execute($buffer);
}
} while ($this->running);
}
public function stop()
{
$this->running = false;
}
}