Initial commit: 投注游戏平台初始化
This commit is contained in:
@@ -0,0 +1,82 @@
|
||||
<?php
|
||||
namespace App\Core;
|
||||
|
||||
class I18n {
|
||||
private static $lang = 'en';
|
||||
private static $translations = [];
|
||||
private static $fallback = [];
|
||||
private static $loaded = false;
|
||||
|
||||
// 支持的语言列表
|
||||
const LANGUAGES = [
|
||||
'en' => 'English',
|
||||
'th' => 'ไทย',
|
||||
'vi' => 'Tiếng Việt',
|
||||
'zh' => '中文',
|
||||
'ms' => 'Bahasa Melayu',
|
||||
'fil' => 'Filipino',
|
||||
'bn' => 'বাংলা',
|
||||
];
|
||||
|
||||
public static function init($db = null) {
|
||||
if (self::$loaded) return;
|
||||
|
||||
// 优先级: URL参数 > Session > Cookie > 浏览器 > 默认en
|
||||
if (!empty($_GET['lang']) && isset(self::LANGUAGES[$_GET['lang']])) {
|
||||
self::$lang = $_GET['lang'];
|
||||
} elseif (!empty($_SESSION['lang'])) {
|
||||
self::$lang = $_SESSION['lang'];
|
||||
} elseif (!empty($_COOKIE['lang'])) {
|
||||
self::$lang = $_COOKIE['lang'];
|
||||
} else {
|
||||
self::$lang = self::detectBrowserLang();
|
||||
}
|
||||
|
||||
$_SESSION['lang'] = self::$lang;
|
||||
setcookie('lang', self::$lang, time() + 86400 * 365, '/');
|
||||
|
||||
self::loadFromFile();
|
||||
self::$loaded = true;
|
||||
}
|
||||
|
||||
private static function detectBrowserLang(): string {
|
||||
$accept = $_SERVER['HTTP_ACCEPT_LANGUAGE'] ?? '';
|
||||
foreach (self::LANGUAGES as $code => $name) {
|
||||
if (stripos($accept, $code) !== false) return $code;
|
||||
}
|
||||
return 'en';
|
||||
}
|
||||
|
||||
private static function loadFromFile() {
|
||||
$file = ROOT_PATH . 'Lang/' . self::$lang . '.php';
|
||||
if (file_exists($file)) {
|
||||
self::$translations = require $file;
|
||||
}
|
||||
// 始终加载英文作为fallback
|
||||
$enFile = ROOT_PATH . 'Lang/en.php';
|
||||
if (file_exists($enFile)) {
|
||||
self::$fallback = require $enFile;
|
||||
}
|
||||
}
|
||||
|
||||
public static function t(string $key, array $params = []): string {
|
||||
$text = self::$translations[$key] ?? self::$fallback[$key] ?? $key;
|
||||
foreach ($params as $k => $v) {
|
||||
$text = str_replace(':' . $k, $v, $text);
|
||||
}
|
||||
return $text;
|
||||
}
|
||||
|
||||
public static function getLang(): string { return self::$lang; }
|
||||
public static function setLang(string $lang) {
|
||||
if (isset(self::LANGUAGES[$lang])) {
|
||||
self::$lang = $lang;
|
||||
self::$loaded = false;
|
||||
self::init();
|
||||
}
|
||||
}
|
||||
public static function getLanguages(): array { return self::LANGUAGES; }
|
||||
}
|
||||
|
||||
// 全局快捷函数
|
||||
function __($key, $params = []) { return I18n::t($key, $params); }
|
||||
Reference in New Issue
Block a user