Переменные через точку

This commit is contained in:
Федор Подлеснов 2015-12-01 15:39:25 +03:00
parent 88fc338b55
commit a993c96f33
3 changed files with 57 additions and 20 deletions

3
.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
*.bak
node_modules
temp

View file

@ -2,8 +2,11 @@
require_once 'klein.php';
echo Klein::render('index.html', array(
$tpl = new Klein();
$tpl->compile('index.html');
echo $tpl->render(array(
'style' => array('style.css'),
'script' => array('script.js'),
'script' => array(array('name' => 'script1.js'), array('name' => 'script2.js')),
'content' => 'test'
));

View file

@ -1,27 +1,58 @@
<?php
class Klein {
static function render($html, $vars) {
$data = file_get_contents($html);
$pattern = array(
"/{%\s*for\s+(\w+)\s+in\s+(\w+)\s*%}/" => "<?php foreach(\$$2 as \$$1): ?>",
"/{%\s*if\s+(\w+)\s*%}/" => "<?php if(isset(\$$1)): ?>",
"/{%\s*block\s+(\w+)\s*%}/" => "<?php function $1() { ?>",
"/{%\s*endblock\s*%}/" => "<?php } ?>",
"/{%\s*endfor\s*%}/" => "<?php endforeach; ?>",
"/{%\s*endif\s*%}/" => "<?php endif; ?>",
"/{{\s*(\w+)\s*}}/" => "<?php echo \$$1; ?>",
);
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 = $data;
$result = file_get_contents($html);
foreach($pattern as $key => $value) {
$result = preg_replace($key, $value, $result);
$result = preg_replace_callback($key, $value, $result);
}
extract($vars);
$this->code = $result;
}
function render($vars) {
extract($vars);
ob_start();
eval(" ?>".$result."<?php ");
eval(" ?>".$this->code."<?php ");
return ob_get_clean();
}
}