2022-09-13 13:14:49 +00:00
|
|
|
<?php
|
|
|
|
namespace Misuzu;
|
|
|
|
|
|
|
|
use InvalidArgumentException;
|
|
|
|
use Twig\Environment as TwigEnvironment;
|
|
|
|
use Twig_Extensions_Extension_Date;
|
|
|
|
use Twig\Loader\FilesystemLoader as TwigLoaderFilesystem;
|
2023-01-01 19:06:01 +00:00
|
|
|
use Misuzu\MszContext;
|
2022-09-13 13:14:49 +00:00
|
|
|
|
|
|
|
final class Template {
|
|
|
|
private const FILE_EXT = '.twig';
|
|
|
|
|
|
|
|
private static $loader;
|
|
|
|
private static $env;
|
|
|
|
private static $vars = [];
|
|
|
|
|
2023-01-01 19:06:01 +00:00
|
|
|
public static function init(MszContext $ctx, ?string $cache = null, bool $debug = false): void {
|
2022-09-13 13:14:49 +00:00
|
|
|
self::$loader = new TwigLoaderFilesystem;
|
|
|
|
self::$env = new TwigEnvironment(self::$loader, [
|
|
|
|
'cache' => $cache ?? false,
|
|
|
|
'strict_variables' => true,
|
|
|
|
'auto_reload' => $debug,
|
|
|
|
'debug' => $debug,
|
|
|
|
]);
|
2023-01-01 19:06:01 +00:00
|
|
|
self::$env->addExtension(new TwigMisuzu($ctx));
|
2022-09-13 13:14:49 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
public static function addPath(string $path): void {
|
|
|
|
self::$loader->addPath($path);
|
|
|
|
}
|
|
|
|
|
|
|
|
public static function renderRaw(string $file, array $vars = []): string {
|
|
|
|
if(!defined('MSZ_TPL_RENDER')) {
|
|
|
|
define('MSZ_TPL_RENDER', microtime(true));
|
|
|
|
}
|
|
|
|
|
|
|
|
if(!str_ends_with($file, self::FILE_EXT)) {
|
|
|
|
$file = str_replace('.', DIRECTORY_SEPARATOR, $file) . self::FILE_EXT;
|
|
|
|
}
|
|
|
|
|
|
|
|
return self::$env->render($file, array_merge(self::$vars, $vars));
|
|
|
|
}
|
|
|
|
|
|
|
|
public static function render(string $file, array $vars = []): void {
|
|
|
|
echo self::renderRaw($file, $vars);
|
|
|
|
}
|
|
|
|
|
|
|
|
public static function set($arrayOrKey, $value = null): void {
|
|
|
|
if(is_string($arrayOrKey)) {
|
|
|
|
self::$vars[$arrayOrKey] = $value;
|
|
|
|
} elseif(is_array($arrayOrKey)) {
|
|
|
|
self::$vars = array_merge(self::$vars, $arrayOrKey);
|
|
|
|
} else {
|
|
|
|
throw new InvalidArgumentException('First parameter must be of type array or string.');
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|