| 1 | <?php |
| 2 | declare(strict_types=1); |
| 3 | |
| 4 | final class I18n |
| 5 | { |
| 6 | /** @var array<string, array<string, string>>|null */ |
| 7 | private static ?array $locales = null; |
| 8 | |
| 9 | public const LOCALES = ['en', 'nl', 'de', 'fr', 'ja', 'zh', 'ko', 'pl', 'ru', 'es']; |
| 10 | |
| 11 | public static function locale(): string |
| 12 | { |
| 13 | $c = $_COOKIE['allianties-locale'] ?? ''; |
| 14 | $c = is_string($c) ? strtolower($c) : ''; |
| 15 | if ($c === 'zh-hans' || $c === 'zh-cn') { |
| 16 | $c = 'zh'; |
| 17 | } |
| 18 | return in_array($c, self::LOCALES, true) ? $c : 'en'; |
| 19 | } |
| 20 | |
| 21 | public static function t(string $key, array $params = [], ?string $locale = null): string |
| 22 | { |
| 23 | $locale = $locale ?? self::locale(); |
| 24 | if (self::$locales === null) { |
| 25 | $raw = @file_get_contents(__DIR__ . '/i18n.json'); |
| 26 | $data = $raw ? json_decode($raw, true) : null; |
| 27 | self::$locales = is_array($data['locales'] ?? null) ? $data['locales'] : []; |
| 28 | } |
| 29 | $s = self::$locales[$locale][$key] ?? self::$locales['en'][$key] ?? $key; |
| 30 | foreach ($params as $k => $v) { |
| 31 | $s = str_replace('{' . $k . '}', (string) $v, $s); |
| 32 | } |
| 33 | return $s; |
| 34 | } |
| 35 | |
| 36 | public static function htmlLang(?string $locale = null): string |
| 37 | { |
| 38 | $map = [ |
| 39 | 'en' => 'en', 'nl' => 'nl', 'de' => 'de', 'fr' => 'fr', 'ja' => 'ja', |
| 40 | 'zh' => 'zh-Hans', 'ko' => 'ko', 'pl' => 'pl', 'ru' => 'ru', 'es' => 'es', |
| 41 | ]; |
| 42 | $locale = $locale ?? self::locale(); |
| 43 | return $map[$locale] ?? 'en'; |
| 44 | } |
| 45 | } |
projects-timfalken-com allianties