58 lines
1.6 KiB
PHP
58 lines
1.6 KiB
PHP
<?php
|
|
|
|
class Klein {
|
|
private $code;
|
|
|
|
function compile($html) {
|
|
$arg = function($name) {
|
|
$list = explode(".", $name);
|
|
$first = array_shift($list);
|
|
return "\$$first" . implode("", array_map(function($x) { return "['$x']"; }, $list));
|
|
};
|
|
|
|
$var = "(\w+(\s*\.\s*\w+)*)";
|
|
|
|
list($for, $endfor, $if, $endif) = array_map(
|
|
function ($args) {
|
|
$body = implode($args, "\s*");
|
|
return "/{%\s*$body\s*%}/";
|
|
},[
|
|
['for', $var, 'in', $var],
|
|
['endfor'],
|
|
['if', $var],
|
|
['endif']
|
|
]);
|
|
|
|
$pattern = [
|
|
$for => function ($x) use($arg) {
|
|
return "<?php foreach({$arg($x[3])} as {$arg($x[1])}): ?>";
|
|
},
|
|
$endfor => function ($x) {
|
|
return "<?php endforeach; ?>";
|
|
},
|
|
$if => function ($x) use ($arg) {
|
|
return "<?php if(isset({$arg($x[1])})): ?>";
|
|
},
|
|
$endif => function ($x) {
|
|
return "<?php endif; ?>";
|
|
},
|
|
"/{{\s*$var\s*}}/" => function ($x) use ($arg) {
|
|
return "<?php echo {$arg($x[1])}; ?>";
|
|
},
|
|
];
|
|
|
|
$result = file_get_contents($html);
|
|
foreach($pattern as $key => $value) {
|
|
$result = preg_replace_callback($key, $value, $result);
|
|
}
|
|
|
|
$this->code = $result;
|
|
}
|
|
|
|
function render($vars) {
|
|
extract($vars);
|
|
ob_start();
|
|
eval(" ?>".$this->code."<?php ");
|
|
return ob_get_clean();
|
|
}
|
|
}
|