misuzu/src/Template.php
2023-08-31 21:33:34 +00:00

60 lines
1.9 KiB
PHP

<?php
namespace Misuzu;
use InvalidArgumentException;
use Sasae\SasaeContext;
use Sasae\SasaeEnvironment;
use Misuzu\MisuzuContext;
final class Template {
private const FILE_EXT = '.twig';
private static SasaeEnvironment $env;
private static array $vars = [];
public static function init(SasaeEnvironment $env): void {
self::$env = $env;
}
public static function addFunction(string $name, callable $body): void {
self::$env->addFunction($name, $body);
}
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);
}
}