Files
da-postgresql/exec/lib/Lang.php
T
2026-07-04 16:00:04 +02:00

79 lines
1.7 KiB
PHP

<?php
declare(strict_types=1);
final class Lang
{
/** @var array<string,string> */
private array $map;
/**
* @param array<string,string> $map
*/
private function __construct(array $map)
{
$this->map = $map;
}
public static function load(string $code): self
{
$code = strtolower(trim($code));
if ($code !== 'pl' && $code !== 'en') {
$code = 'en';
}
$path = PLUGIN_ROOT . '/lang/' . $code . '.php';
if (!is_file($path)) {
$path = PLUGIN_ROOT . '/lang/en.php';
}
$map = [];
if (is_file($path)) {
$data = require $path;
if (is_array($data)) {
$map = $data;
}
}
return new self($map);
}
/**
* @param array<string,string|int|float> $vars
*/
public function t(string $key, array $vars = []): string
{
$text = $this->map[$key] ?? $key;
foreach ($vars as $var => $value) {
$text = str_replace('{' . $var . '}', (string)$value, $text);
}
return $text;
}
public function translateHtml(string $html): string
{
if ($html === '' || empty($this->map)) {
return $html;
}
$keys = array_keys($this->map);
usort($keys, static function (string $a, string $b): int {
return strlen($b) <=> strlen($a);
});
$values = [];
foreach ($keys as $key) {
$values[] = $this->map[$key];
}
return str_replace($keys, $values, $html);
}
/**
* @return string[]
*/
public function keys(): array
{
return array_keys($this->map);
}
}