klein/klein.php

40 lines
1.4 KiB
PHP

<?php
class Klein {
private $code;
function compile($html) {
$pattern = array_map(function ($grammar) {
list(, $result) = $grammar;
$body = strtr($grammar[0], [" " => "\s*", "+" => "\s+", ":var" => "(\w+(\s*\.\s*\w+)*)", ":id" => "(\w+)"]);
return ["/$body/",
function ($x) use ($result) {
return "<?php " . preg_replace_callback("/#(\d+)/", function ($s) use($x) {
return preg_replace("/\.\s*(\w+)/", "['$1']", $x[$s[1]]);
}, $result) . " ?>";
}];
}, [
["{% for+:id+in+:var %}", "foreach(\$#2 as \$index => \$#1): \$loop = ['first' => \$index == 0, 'last' => \$index == count(\$#2) - 1];"],
["{% for+:id , :id+in+:var %}", "foreach(\$#3 as \$#1 => \$#2):"],
["{% endfor %}", "endforeach;"],
["{% if+:var %}", "if(isset(\$#1) && \$#1 ):"],
["{% endif %}", "endif;"],
["{{ :var }}", "echo \$#1;"],
["{{ :var\|:id }}", "echo #3(\$#1);"]
]);
$result = file_get_contents($html);
foreach($pattern as $arg) {
$result = preg_replace_callback($arg[0], $arg[1], $result);
}
$this->code = $result;
}
function render($vars) {
extract($vars);
ob_start();
eval(" ?>".$this->code."<?php ");
return ob_get_clean();
}
}