misuzu/src/Template.php

67 lines
2 KiB
PHP
Raw Normal View History

<?php
namespace Misuzu;
use InvalidArgumentException;
2024-10-05 02:40:29 +00:00
use Index\Templating\TplEnvironment;
final class Template {
private const FILE_EXT = '.twig';
2024-10-05 02:40:29 +00:00
private static TplEnvironment $env;
2024-12-02 21:33:15 +00:00
/** @var array<string, mixed> */
2023-08-31 21:33:34 +00:00
private static array $vars = [];
2024-10-05 02:40:29 +00:00
public static function init(TplEnvironment $env): void {
2023-08-31 21:33:34 +00:00
self::$env = $env;
}
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
}
2024-12-02 21:33:15 +00:00
/** @param array<string, mixed> $vars */
public static function renderRaw(string $file, array $vars = []): string {
2023-08-31 21:33:34 +00:00
if(!defined('MSZ_TPL_RENDER'))
define('MSZ_TPL_RENDER', microtime(true));
2023-08-31 21:33:34 +00:00
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));
}
2024-12-02 21:33:15 +00:00
/** @param array<string, mixed> $vars */
public static function render(string $file, array $vars = []): void {
echo self::renderRaw($file, $vars);
}
2024-12-02 21:33:15 +00:00
/**
* @param string|array<string|int, mixed> $arrayOrKey
* @param mixed $value
*/
public static function set($arrayOrKey, $value = null): void {
2023-08-31 21:33:34 +00:00
if(is_string($arrayOrKey))
self::$vars[$arrayOrKey] = $value;
2023-08-31 21:33:34 +00:00
elseif(is_array($arrayOrKey))
self::$vars = array_merge(self::$vars, $arrayOrKey);
2023-08-31 21:33:34 +00:00
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);
}
}