Translate.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * MINZ - Copyright 2011 Marien Fressinaud
  5. * Sous licence AGPL3 <http://www.gnu.org/licenses/>
  6. */
  7. /**
  8. * This class is used for the internationalization.
  9. * It uses files in `./app/i18n/`
  10. */
  11. class Minz_Translate {
  12. public const DEFAULT_LANGUAGE = 'en';
  13. /**
  14. * $path_list is the list of registered base path to search translations.
  15. * @var array<string>
  16. */
  17. private static array $path_list = [];
  18. /**
  19. * $lang_name is the name of the current language to use.
  20. */
  21. private static string $lang_name = '';
  22. /**
  23. * $lang_files is a list of registered i18n files.
  24. * @var array<string,array<string>>
  25. */
  26. private static array $lang_files = [];
  27. /**
  28. * Dedicated plural catalogue files registered for the current language.
  29. * @var array<int,array{path:string,use_formula:bool}>
  30. */
  31. private static array $plural_files = [];
  32. /**
  33. * $translates is a cache for i18n translation.
  34. * @var array<string,mixed>
  35. */
  36. private static array $translates = [];
  37. /**
  38. * Cache of normalised plural message families by i18n key.
  39. * @var array<string,array<int,string>>
  40. */
  41. private static array $plural_message_families = [];
  42. private static bool $plural_catalogue_loaded = false;
  43. private static ?int $plural_count = null;
  44. private static ?\Closure $plural_function = null;
  45. /**
  46. * Init the translation object.
  47. * @param string $lang_name the lang to show.
  48. */
  49. public static function init(string $lang_name = ''): void {
  50. self::$lang_name = $lang_name;
  51. self::$lang_files = [];
  52. self::$plural_files = [];
  53. self::$translates = [];
  54. self::$plural_message_families = [];
  55. self::resetPluralCache();
  56. self::registerPath(APP_PATH . '/i18n');
  57. foreach (self::$path_list as $path) {
  58. self::loadLang($path);
  59. }
  60. }
  61. /**
  62. * Reset the translation object with a new language.
  63. * @param string $lang_name the new language to use
  64. */
  65. public static function reset(string $lang_name): void {
  66. self::$lang_name = $lang_name;
  67. self::$lang_files = [];
  68. self::$plural_files = [];
  69. self::$translates = [];
  70. self::$plural_message_families = [];
  71. self::resetPluralCache();
  72. foreach (self::$path_list as $path) {
  73. self::loadLang($path);
  74. }
  75. }
  76. /**
  77. * Return the list of available languages.
  78. * @return list<string> containing langs found in different registered paths.
  79. */
  80. public static function availableLanguages(): array {
  81. $list_langs = [];
  82. self::registerPath(APP_PATH . '/i18n');
  83. foreach (self::$path_list as $path) {
  84. $scan = scandir($path);
  85. if (is_array($scan)) {
  86. $path_langs = array_values(array_diff(
  87. $scan,
  88. ['..', '.']
  89. ));
  90. $list_langs = array_merge($list_langs, $path_langs);
  91. }
  92. }
  93. return array_values(array_unique($list_langs));
  94. }
  95. public static function exists(string $lang): bool {
  96. return in_array($lang, Minz_Translate::availableLanguages(), true);
  97. }
  98. /**
  99. * Return the language to use in the application.
  100. * It returns the connected language if it exists then returns the first match from the
  101. * preferred languages then returns the default language
  102. * @param string|null $user the connected user language (nullable)
  103. * @param array<string> $preferred an array of the preferred languages
  104. * @param string|null $default the preferred language to use
  105. * @return string containing the language to use
  106. */
  107. public static function getLanguage(?string $user, array $preferred, ?string $default): string {
  108. if (null !== $user) {
  109. if (!self::exists($user)) return self::DEFAULT_LANGUAGE;
  110. return $user;
  111. }
  112. $languages = Minz_Translate::availableLanguages();
  113. foreach ($preferred as $language) {
  114. $language = strtolower($language);
  115. if (in_array($language, $languages, true)) {
  116. return $language;
  117. }
  118. }
  119. return $default ?: self::DEFAULT_LANGUAGE;
  120. }
  121. /**
  122. * Register a new path.
  123. * @param string $path a path containing i18n directories (e.g. ./en/, ./fr/).
  124. */
  125. public static function registerPath(string $path): void {
  126. if (!in_array($path, self::$path_list, true) && is_dir($path)) {
  127. self::$path_list[] = $path;
  128. self::loadLang($path);
  129. }
  130. }
  131. /**
  132. * Load translations of the current language from the given path.
  133. * @param string $path the path containing i18n directories.
  134. */
  135. private static function loadLang(string $path): void {
  136. $selected_lang_path = $path . '/' . self::$lang_name;
  137. $lang_path = $path . '/' . self::$lang_name;
  138. $uses_selected_language = self::$lang_name !== '' && is_dir($selected_lang_path);
  139. if (!$uses_selected_language) {
  140. // The lang path does not exist, fallback to English ('en')
  141. $lang_path = $path . '/en';
  142. if (!is_dir($lang_path)) {
  143. // English ('en') i18n files not provided. Stop here. The keys will be shown.
  144. return;
  145. }
  146. }
  147. $list_i18n_files = array_values(array_diff(
  148. scandir($lang_path) ?: [],
  149. ['..', '.']
  150. ));
  151. self::$plural_message_families = [];
  152. // Each file basename correspond to a top-level i18n key. For each of
  153. // these keys we store the file pathname and mark translations must be
  154. // reloaded (by setting $translates[$i18n_key] to null).
  155. foreach ($list_i18n_files as $i18n_filename) {
  156. if ($i18n_filename === 'plurals.php') {
  157. self::$plural_files[] = [
  158. 'path' => $lang_path . '/' . $i18n_filename,
  159. 'use_formula' => $uses_selected_language || self::$lang_name === '',
  160. ];
  161. self::resetPluralCache();
  162. continue;
  163. }
  164. $i18n_key = basename($i18n_filename, '.php');
  165. if (!isset(self::$lang_files[$i18n_key])) {
  166. self::$lang_files[$i18n_key] = [];
  167. }
  168. self::$lang_files[$i18n_key][] = $lang_path . '/' . $i18n_filename;
  169. self::$translates[$i18n_key] = null;
  170. }
  171. }
  172. /**
  173. * Load the files associated to $key into $translates.
  174. * @param string $key the top level i18n key we want to load.
  175. */
  176. private static function loadKey(string $key): bool {
  177. // The top level key is not in $lang_files, it means it does not exist!
  178. if (!isset(self::$lang_files[$key])) {
  179. Minz_Log::debug($key . ' is not a valid top level key');
  180. return false;
  181. }
  182. self::$translates[$key] = [];
  183. foreach (self::$lang_files[$key] as $lang_pathname) {
  184. $i18n_array = include $lang_pathname;
  185. if (!is_array($i18n_array)) {
  186. Minz_Log::warning('`' . $lang_pathname . '` does not contain a PHP array');
  187. continue;
  188. }
  189. // We must avoid to erase previous data so we just override them if
  190. // needed.
  191. self::$translates[$key] = array_replace_recursive(
  192. self::$translates[$key], $i18n_array
  193. );
  194. }
  195. return true;
  196. }
  197. /**
  198. * Translate a key into its corresponding value based on selected language.
  199. * @param string $key the key to translate.
  200. * @param bool|float|int|string ...$args additional parameters for variable keys.
  201. * @return string value corresponding to the key.
  202. * If no value is found, return the key itself.
  203. */
  204. public static function t(string $key, ...$args): string {
  205. $translation_value = self::resolveKey($key);
  206. if ($translation_value === null) {
  207. return $key;
  208. }
  209. if (!is_string($translation_value)) {
  210. $translation_value = $translation_value['_'] ?? null;
  211. if (!is_string($translation_value)) {
  212. Minz_Log::debug($key . ' is not a valid key');
  213. return $key;
  214. }
  215. }
  216. // Get the facultative arguments to replace i18n variables.
  217. return empty($args) ? $translation_value : vsprintf($translation_value, $args);
  218. }
  219. /**
  220. * Resolve a translation key to its raw string or array value.
  221. * @return array<mixed>|string|null
  222. */
  223. private static function resolveKey(string $key): array|string|null {
  224. $group = explode('.', $key);
  225. if (count($group) < 2) {
  226. Minz_Log::debug($key . ' is not in a valid format');
  227. $top_level = 'gen';
  228. } else {
  229. $top_level = array_shift($group) ?? '';
  230. }
  231. if ((self::$translates[$top_level] ?? null) === null) {
  232. $res = self::loadKey($top_level);
  233. if (!$res) {
  234. return null;
  235. }
  236. }
  237. $translationValue = self::$translates[$top_level] ?? null;
  238. if (!is_array($translationValue)) {
  239. return null;
  240. }
  241. foreach ($group as $i18n_level) {
  242. if (!is_array($translationValue) || !array_key_exists($i18n_level, $translationValue)) {
  243. Minz_Log::debug($key . ' is not a valid key');
  244. return null;
  245. }
  246. $translationValue = $translationValue[$i18n_level];
  247. }
  248. if (!is_array($translationValue) && !is_string($translationValue)) {
  249. return null;
  250. }
  251. return $translationValue;
  252. }
  253. /**
  254. * Return the current language.
  255. */
  256. public static function language(): string {
  257. return self::$lang_name;
  258. }
  259. /**
  260. * Reset all cached plural data.
  261. */
  262. private static function resetPluralCache(): void {
  263. self::$plural_catalogue_loaded = false;
  264. self::$plural_count = null;
  265. self::$plural_function = null;
  266. }
  267. /**
  268. * Load the plural catalogue for the current language.
  269. */
  270. private static function loadPluralCatalogue(): void {
  271. if (self::$plural_catalogue_loaded) {
  272. return;
  273. }
  274. self::$plural_catalogue_loaded = true;
  275. $fallbackPluralCount = null;
  276. $fallbackPluralFunction = null;
  277. foreach (self::$plural_files as $pluralFile) {
  278. $pluralData = include $pluralFile['path'];
  279. if (!is_array($pluralData)) {
  280. Minz_Log::warning('`' . $pluralFile['path'] . '` does not contain a PHP array');
  281. continue;
  282. }
  283. $pluralCount = $pluralData['nplurals'] ?? null;
  284. $pluralFunction = $pluralData['plural'] ?? null;
  285. if (!is_int($pluralCount) || $pluralCount < 1 || !($pluralFunction instanceof \Closure)) {
  286. Minz_Log::warning('Invalid compiled plural data in `' . $pluralFile['path'] . '`. Run `make fix-all`.');
  287. continue;
  288. }
  289. if ($pluralFile['use_formula']) {
  290. if (self::$plural_function === null) {
  291. self::$plural_count = $pluralCount;
  292. self::$plural_function = $pluralFunction;
  293. } elseif (self::$plural_count !== $pluralCount) {
  294. Minz_Log::warning('Conflicting compiled plural count in `' . $pluralFile['path'] . '`');
  295. }
  296. } elseif ($fallbackPluralFunction === null) {
  297. $fallbackPluralCount = $pluralCount;
  298. $fallbackPluralFunction = $pluralFunction;
  299. }
  300. }
  301. if (self::$plural_function === null) {
  302. self::$plural_count = $fallbackPluralCount;
  303. self::$plural_function = $fallbackPluralFunction;
  304. }
  305. }
  306. private static function pluralIndex(int $value): ?int {
  307. if (self::$plural_count === null || self::$plural_function === null) {
  308. return null;
  309. }
  310. $index = (self::$plural_function)($value);
  311. if (!is_int($index)) {
  312. return null;
  313. }
  314. $index = max(0, $index);
  315. return min($index, self::$plural_count - 1);
  316. }
  317. /**
  318. * Translate a count-based key using gettext plural indexes.
  319. * @param string $baseKey Base i18n key without plural suffix (e.g. `gen.interval.second`).
  320. * @param int $value Count used for plural category and `%d` substitution.
  321. * @return string|null Translated string or null if no translation is found.
  322. */
  323. public static function plural(string $baseKey, int $value): ?string {
  324. self::loadPluralCatalogue();
  325. if (!isset(self::$plural_message_families[$baseKey])) {
  326. $rawMessageFamily = self::resolveKey($baseKey);
  327. if (!is_array($rawMessageFamily) || $rawMessageFamily === []) {
  328. Minz_Log::debug($baseKey . ' is not a valid plural key');
  329. return null;
  330. }
  331. /** @var array<int,string> $messageFamily */
  332. $messageFamily = [];
  333. foreach ($rawMessageFamily as $index => $message) {
  334. if (is_int($index)) {
  335. $integerIndex = $index;
  336. } elseif (ctype_digit($index)) {
  337. $integerIndex = (int)$index;
  338. } else {
  339. $integerIndex = null;
  340. }
  341. if ($integerIndex === null) {
  342. continue;
  343. }
  344. if (!is_string($message)) {
  345. continue;
  346. }
  347. $messageFamily[$integerIndex] = $message;
  348. }
  349. if ($messageFamily === []) {
  350. Minz_Log::debug($baseKey . ' is not a valid plural key');
  351. return null;
  352. }
  353. ksort($messageFamily);
  354. self::$plural_message_families[$baseKey] = $messageFamily;
  355. }
  356. $messageFamily = self::$plural_message_families[$baseKey];
  357. $index = self::pluralIndex($value);
  358. if ($index !== null && isset($messageFamily[$index]) && $messageFamily[$index] !== '') {
  359. return vsprintf($messageFamily[$index], [$value]);
  360. }
  361. $lastMessage = end($messageFamily);
  362. if ($lastMessage === false || $lastMessage === '') {
  363. return null;
  364. }
  365. return vsprintf($lastMessage, [$value]);
  366. }
  367. }
  368. /**
  369. * Alias for Minz_Translate::t()
  370. */
  371. function _t(string $key, bool|float|int|string ...$args): string {
  372. return Minz_Translate::t($key, ...$args);
  373. }