blob: 6f764197367390a43082f4f2d07298ebca2251b5 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
<?php
// Minimal i18n helper. Detects language from the current filename suffix
// (_jp.php / _zh.php) so it matches the existing URL scheme, and loads a
// flat key -> string dict from locales/{code}.php.
//
// Usage in a page:
// require_once __DIR__ . '/../partials/i18n.php'; // adjust relative path
// echo t('home.title');
//
// Missing keys fall back to the English dict, then to the key itself.
if (!function_exists('t')) {
function _i18n_lang(): string {
// Prefer SCRIPT_NAME: under nginx + php-fpm, PHP_SELF is often empty.
$f = basename((string)($_SERVER['SCRIPT_NAME'] ?? $_SERVER['PHP_SELF'] ?? 'index.php'));
if ($f === '') $f = 'index.php';
if (str_ends_with($f, '_zh.php')) return 'zh';
if (str_ends_with($f, '_jp.php')) return 'ja';
return 'en';
}
function _i18n_load(string $code): array {
static $cache = [];
if (isset($cache[$code])) return $cache[$code];
$path = __DIR__ . '/../locales/' . $code . '.php';
$cache[$code] = is_file($path) ? (array)include $path : [];
return $cache[$code];
}
function t(string $key, ?string $lang = null): string {
$lang = $lang ?? _i18n_lang();
$dict = _i18n_load($lang);
if (array_key_exists($key, $dict)) return $dict[$key];
if ($lang !== 'en') {
$en = _i18n_load('en');
if (array_key_exists($key, $en)) return $en[$key];
}
return $key;
}
}
|