misuzu/src/Template.php

61 lines
1.9 KiB
PHP
Raw Normal View History

2022-09-13 13:14:49 +00:00
<?php
namespace Misuzu;
use InvalidArgumentException;
2023-08-31 21:33:34 +00:00
use Sasae\SasaeContext;
use Sasae\SasaeEnvironment;
use Misuzu\MisuzuContext;
2022-09-13 13:14:49 +00:00
final class Template {
private const FILE_EXT = '.twig';
2023-08-31 21:33:34 +00:00
private static SasaeEnvironment $env;
private static array $vars = [];
2022-09-13 13:14:49 +00:00
2023-08-31 21:33:34 +00:00
public static function init(SasaeEnvironment $env): void {
self::$env = $env;
2022-09-13 13:14:49 +00:00
}
2023-08-28 01:17:34 +00:00
public static function addFunction(string $name, callable $body): void {
2023-08-31 21:33:34 +00:00
self::$env->addFunction($name, $body);
2023-08-28 01:17:34 +00:00
}
2022-09-13 13:14:49 +00:00
public static function renderRaw(string $file, array $vars = []): string {
2023-08-31 21:33:34 +00:00
if(!defined('MSZ_TPL_RENDER'))
2022-09-13 13:14:49 +00:00
define('MSZ_TPL_RENDER', microtime(true));
2023-08-31 21:33:34 +00:00
if(!str_ends_with($file, self::FILE_EXT))
2022-09-13 13:14:49 +00:00
$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 {
2023-08-31 21:33:34 +00:00
if(is_string($arrayOrKey))
2022-09-13 13:14:49 +00:00
self::$vars[$arrayOrKey] = $value;
2023-08-31 21:33:34 +00:00
elseif(is_array($arrayOrKey))
2022-09-13 13:14:49 +00:00
self::$vars = array_merge(self::$vars, $arrayOrKey);
2023-08-31 21:33:34 +00:00
else
2022-09-13 13:14:49 +00:00
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
}