Skip to content

Instantly share code, notes, and snippets.

@audinue
Created May 12, 2024 04:59
Show Gist options
  • Save audinue/c38da356a958fa0b75723efac6906d8e to your computer and use it in GitHub Desktop.
Save audinue/c38da356a958fa0b75723efac6906d8e to your computer and use it in GitHub Desktop.
<?php
namespace tiny_blade;
function _replace(string $template): string
{
// @endif
$template = preg_replace('/^\s*@(end.+?)\s*$/m', '<?php $1 ?>', $template);
// @if ($foo)
$template = preg_replace('/^\s*@(.+?)\s*$/m', '<?php $1: ?>', $template);
// @checked($foo)
$template = preg_replace('/\s+@(.+?)\((.+?)\)/', '<?= ($2) ? " $1" : "" ?>', $template);
// {{ $foo }}
$template = preg_replace('/{{\s*(.+?)\s*}}/', '<?= htmlspecialchars($1) ?>', $template);
// {!! $foo !!}
$template = preg_replace('/{!!\s*(.+?)\s*!!}/', '<?= $1 ?>', $template);
return $template;
}
function _compile(string $name): string
{
$source = "templates/$name.blade.php";
$target = "templates/_cache/$name.php";
if (!is_file($target) || filemtime($source) != filemtime($target)) {
$target_dir = dirname($target);
if (!is_dir($target_dir)) {
mkdir($target_dir, 0777, true);
}
file_put_contents($target, _replace(file_get_contents($source)));
touch($target, filemtime($source));
}
return $target;
}
function render(string $_name, array $_args = []): string
{
$_target = _compile($_name);
extract($_args);
ob_start();
include $_target;
return ob_get_clean();
}
function evaluate(string $_template, ...$_args): string
{
extract($_args);
ob_start();
eval('?>' . _replace($_template));
return ob_get_clean();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment