<?php
namespace Boris;
class ReadlineClient {
private $_socket;
private $_prompt;
private $_historyFile;
private $_clear = false;
public function __construct($socket) {
$this->_socket = $socket;
}
public function start($prompt, $historyFile) {
readline_read_history($historyFile);
declare(ticks = 1);
pcntl_signal(SIGCHLD, SIG_IGN);
pcntl_signal(SIGINT, array($this, 'clear'), true);
if (fread($this->_socket, 1) != EvalWorker::READY) {
throw new \RuntimeException('EvalWorker failed to start');
}
$parser = new ShallowParser();
$buf = '';
$lineno = 1;
for (;;) {
$this->_clear = false;
$line = readline(
sprintf(
'[%d] %s',
$lineno,
($buf == ''
? $prompt
: str_pad('*> ', strlen($prompt), ' ', STR_PAD_LEFT))
)
);
if ($this->_clear) {
$buf = '';
continue;
}
if (false === $line) {
$buf = 'exit(0);'; }
if (strlen($line) > 0) {
readline_add_history($line);
}
$buf .= sprintf("%s\n", $line);
if ($statements = $parser->statements($buf)) {
++$lineno;
$buf = '';
foreach ($statements as $stmt) {
if (false === $written = fwrite($this->_socket, $stmt)) {
throw new \RuntimeException('Socket error: failed to write data');
}
if ($written > 0) {
$status = fread($this->_socket, 1);
if ($status == EvalWorker::EXITED) {
readline_write_history($historyFile);
echo "\n";
exit(0);
} elseif ($status == EvalWorker::FAILED) {
break;
}
}
}
}
}
}
public function clear() {
$this->_clear = true;
}
}