misuzu/src/Template.php

78 lines
2.5 KiB
PHP
Raw Normal View History

2022-09-13 13:14:49 +00:00
<?php
namespace Misuzu;
use InvalidArgumentException;
use Twig\Environment as TwigEnvironment;
2023-08-28 01:17:34 +00:00
use Twig\TwigFunction;
2022-09-13 13:14:49 +00:00
use Twig_Extensions_Extension_Date;
use Twig\Loader\FilesystemLoader as TwigLoaderFilesystem;
use Misuzu\MisuzuContext;
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 = [];
public static function init(MisuzuContext $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,
]);
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);
}
2023-08-28 01:17:34 +00:00
public static function addFunction(string $name, callable $body): void {
self::$env->addFunction(new TwigFunction($name, $body));
}
2022-09-13 13:14:49 +00:00
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.');
}
}
public static function displayInfo(?string $message, int $statusCode, ?string $template = null): never {
http_response_code($statusCode);
self::$vars['http_code'] = $statusCode;
if(!empty($message))
self::$vars['message'] = $message;
self::render(sprintf($template ?? 'errors.%d', $statusCode));
exit;
}
public static function throwError(int $statusCode, ?string $template = null): never {
self::displayInfo(null, $statusCode, $template);
}
2022-09-13 13:14:49 +00:00
}