Skip to content

Instantly share code, notes, and snippets.

@jkaflik
Created April 5, 2010 17:38
Show Gist options
  • Save jkaflik/356635 to your computer and use it in GitHub Desktop.
Save jkaflik/356635 to your computer and use it in GitHub Desktop.
<?php
class ErrorHandler
{
public static function initalize()
{
set_error_handler( array("ErrorHandler", "handle") );
}
public static function handle($errno, $errstr, $errfile, $errline, $errcontext)
{
throw new Exception($errstr, $errline);
}
}
class CodeInterpreter
{
private $console = null;
private $currentCode = "";
public $blocks = 0;
public function __construct($console)
{
$this->console = $console;
}
public function run($code)
{
$this->currentCode .= $code;
if( strpos($code,"{") !== false )
{
$this->blocks++;
}
if( strpos($code,"}") !== false )
{
$this->blocks--;
}
if( $this->blocks == 0 )
{
$b = $this->currentCode;
$this->currentCode = "";
return $b;
}
}
}
class Console
{
private $ci = null;
public function __construct()
{
$this->ci = new CodeInterpreter(&$this);
ErrorHandler::initalize();
}
public function run()
{
while( true )
{
for( $i=0;$i<=$this->ci->blocks;$i++ )
{
echo ">>";
}
echo " ";
$stdin = fopen("php://stdin", "r");
$input = fgets($stdin,1024*1024);
fclose($stdin);
if( $input == 'quit' || $input == 'exit' )
{
break;
}
$o = $this->ci->run($input);
if( $o )
{
try
{
eval($o);
}
catch( Exception $e )
{
$this->exception($e);
}
}
}
}
public function exception($e)
{
echo "Exception:\t\t" . $e->getMessage() . "\n\t\tfrom " . $e->getFile() . ":" . $e->getLine() . "\n";
}
}
$c = new Console;
$c->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment