*/ private array $map; private string $code; /** * @param array $map */ private function __construct(string $code, array $map) { $this->code = $code; $this->map = $map; } public static function load(string $preferred, Settings $settings): self { $candidates = [strtolower(trim($preferred)), $settings->defaultLanguage(), 'en']; foreach ($candidates as $code) { if (!preg_match('/^[a-z]{2}$/', $code)) { continue; } $path = PLUGIN_ROOT . '/lang/' . $code . '.php'; if (is_file($path)) { $data = require $path; return new self($code, is_array($data) ? $data : []); } } return new self('en', []); } public function code(): string { return $this->code; } /** * @param array $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 fn (string $a, string $b): int => strlen($b) <=> strlen($a)); return str_replace($keys, array_map(fn (string $k): string => $this->map[$k], $keys), $html); } }