Немного оптимизировал
This commit is contained in:
parent
f02a0bac42
commit
a49f10601b
3 changed files with 19 additions and 27 deletions
39
klein.php
39
klein.php
|
|
@ -4,38 +4,29 @@ 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));
|
||||
};
|
||||
|
||||
$rx = function ($grammar) use ($arg) {
|
||||
list($pattern, $result) = $grammar;
|
||||
$body = strtr($pattern, [" " => "\s*", "+" => "\s+", ":v" => "(\w+(\s*\.\s*\w+)*)", ":x" => "(\w+)"]);
|
||||
$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, $arg) {
|
||||
$body = preg_replace_callback("/#(\d+)/", function ($s) use($x, $arg) {
|
||||
return $arg($x[$s[1]]);
|
||||
}, $result);
|
||||
return "<?php $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) . " ?>";
|
||||
}];
|
||||
};
|
||||
|
||||
$pattern = array_map($rx, [
|
||||
["{% for+:v+in+:v %}", "foreach(\$#3 as \$n => \$#1): \$loop = ['first' => \$n == 0];"],
|
||||
}, [
|
||||
["{% for+:id+in+:var %}", "foreach(\$#2 as \$index => \$#1): \$loop = ['first' => \$index == 0, 'last' => \$index == count(\$#2) - 1];"],
|
||||
["{% endfor %}", "endforeach;"],
|
||||
["{% if+:v %}", "if(isset(\$#1) && \$#1 ):"],
|
||||
["{% if+:var %}", "if(isset(\$#1) && \$#1 ):"],
|
||||
["{% endif %}", "endif;"],
|
||||
["{{ :v }}", "echo \$#1;"],
|
||||
["{{ :v\|:x }}", "echo #3(\$#1);"]
|
||||
["{{ :var }}", "echo \$#1;"],
|
||||
["{{ :var\|:id }}", "echo #3(\$#1);"]
|
||||
]);
|
||||
|
||||
|
||||
$result = file_get_contents($html);
|
||||
foreach($pattern as $arg) {
|
||||
list($key, $value) = $arg;
|
||||
$result = preg_replace_callback($key, $value, $result);
|
||||
$result = preg_replace_callback($arg[0], $arg[1], $result);
|
||||
}
|
||||
|
||||
$this->code = $result;
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue