*/ private array $map; /** * @param array $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 $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); } }