Last active
August 6, 2016 20:44
-
-
Save jm42/3675fa8a2aa47d9c2aebd3ade9780255 to your computer and use it in GitHub Desktop.
Variable template in mustache style
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function mustache(array $context) { | |
return function($resource) use($context) { | |
$handler = resource_of($resource); | |
$state = @out; | |
$tag = ''; | |
while (!feof($handler)) { | |
$out = fgets($handler); | |
$len = strlen($out); | |
$pos = 0; | |
for ($i = $pos; $i < $len; $i++) { | |
if ($state === @out && $out[$i] === '{' && ($out[$i+1] ?? '') === '{') { | |
yield substr($out, $pos, $i - $pos); | |
$pos = $i + 2; | |
$tag = ''; | |
$state = @tag; | |
} elseif ($state === @tag && $out[$i] === '}' && ($out[$i+1] ?? '') === '}') { | |
$tag = trim($tag . substr($out, $pos, $i - $pos)); | |
$pos = $i + 2; | |
$state = @out; | |
switch ($tag[0]) { | |
default: | |
if (!isset($context[$tag])) { | |
throw new \RuntimeException("Variable \"$tag\" not found"); | |
} | |
yield $context[$tag]; // TODO escape | |
} | |
} | |
} | |
if ($state === @out) { | |
yield substr($out, $pos); | |
} elseif ($state === @tag) { | |
$tag .= substr($out, $pos); | |
} | |
} | |
if ($state === @tag) { | |
throw new \LogicException('Unbalanced tags'); | |
} | |
fclose($handler); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment