php-spark/src/Commands/ReplCommand.php

42 lines
1.4 KiB
PHP

<?php
namespace Spark\Commands;
use Symfony\Component\Console\Attribute\AsCommand;
use Spark\Commands\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
#[AsCommand(name:'repl', description:'Interactive REPL for PHP')]
class ReplCommand extends Command
{
protected function configure()
{
$this->addOption("list", null, InputOption::VALUE_NONE, "List the available scripts");
$this->addArgument("script", InputArgument::OPTIONAL, "The script too run (see --list)");
$this->addArgument("args", InputArgument::OPTIONAL|InputArgument::IS_ARRAY, "Arguments to the script");
}
protected function execute(InputInterface $input, OutputInterface $output)
{
$env = $this->getEnvironment();
while (true) {
$cmd = readline("repl> ");
if ($cmd) readline_add_history($cmd);
try {
$ret = @eval("return {$cmd};");
//$output->writeln(json_encode($ret,JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES));
//$output->writeln("<info>".var_export($ret,true)."</>");
dump($ret);
} catch (\Throwable $t) {
$output->writeln("<error>".$t->getMessage()."</>");
}
}
return Command::SUCCESS;
}
}