Translate.php 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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. /**
  13. * $path_list is the list of registered base path to search translations.
  14. * @var array<string>
  15. */
  16. private static array $path_list = [];
  17. /**
  18. * $lang_name is the name of the current language to use.
  19. */
  20. private static string $lang_name = '';
  21. /**
  22. * $lang_files is a list of registered i18n files.
  23. * @var array<string,array<string>>
  24. */
  25. private static array $lang_files = [];
  26. /**
  27. * $translates is a cache for i18n translation.
  28. * @var array<string,mixed>
  29. */
  30. private static array $translates = [];
  31. /**
  32. * Init the translation object.
  33. * @param string $lang_name the lang to show.
  34. */
  35. public static function init(string $lang_name = ''): void {
  36. self::$lang_name = $lang_name;
  37. self::$lang_files = [];
  38. self::$translates = [];
  39. self::registerPath(APP_PATH . '/i18n');
  40. foreach (self::$path_list as $path) {
  41. self::loadLang($path);
  42. }
  43. }
  44. /**
  45. * Reset the translation object with a new language.
  46. * @param string $lang_name the new language to use
  47. */
  48. public static function reset(string $lang_name): void {
  49. self::$lang_name = $lang_name;
  50. self::$lang_files = [];
  51. self::$translates = [];
  52. foreach (self::$path_list as $path) {
  53. self::loadLang($path);
  54. }
  55. }
  56. /**
  57. * Return the list of available languages.
  58. * @return list<string> containing langs found in different registered paths.
  59. */
  60. public static function availableLanguages(): array {
  61. $list_langs = [];
  62. self::registerPath(APP_PATH . '/i18n');
  63. foreach (self::$path_list as $path) {
  64. $scan = scandir($path);
  65. if (is_array($scan)) {
  66. $path_langs = array_values(array_diff(
  67. $scan,
  68. ['..', '.']
  69. ));
  70. $list_langs = array_merge($list_langs, $path_langs);
  71. }
  72. }
  73. return array_values(array_unique($list_langs));
  74. }
  75. public static function exists(string $lang): bool {
  76. return in_array($lang, Minz_Translate::availableLanguages(), true);
  77. }
  78. /**
  79. * Return the language to use in the application.
  80. * It returns the connected language if it exists then returns the first match from the
  81. * preferred languages then returns the default language
  82. * @param string|null $user the connected user language (nullable)
  83. * @param array<string> $preferred an array of the preferred languages
  84. * @param string|null $default the preferred language to use
  85. * @return string containing the language to use
  86. */
  87. public static function getLanguage(?string $user, array $preferred, ?string $default): string {
  88. if (null !== $user) {
  89. if (!self::exists($user)) return 'en';
  90. return $user;
  91. }
  92. $languages = Minz_Translate::availableLanguages();
  93. foreach ($preferred as $language) {
  94. $language = strtolower($language);
  95. if (in_array($language, $languages, true)) {
  96. return $language;
  97. }
  98. }
  99. return $default == null ? 'en' : $default;
  100. }
  101. /**
  102. * Register a new path.
  103. * @param string $path a path containing i18n directories (e.g. ./en/, ./fr/).
  104. */
  105. public static function registerPath(string $path): void {
  106. if (!in_array($path, self::$path_list, true) && is_dir($path)) {
  107. self::$path_list[] = $path;
  108. self::loadLang($path);
  109. }
  110. }
  111. /**
  112. * Load translations of the current language from the given path.
  113. * @param string $path the path containing i18n directories.
  114. */
  115. private static function loadLang(string $path): void {
  116. $lang_path = $path . '/' . self::$lang_name;
  117. if (self::$lang_name === '' || !is_dir($lang_path)) {
  118. // The lang path does not exist, fallback to English ('en')
  119. $lang_path = $path . '/en';
  120. if (!is_dir($lang_path)) {
  121. // English ('en') i18n files not provided. Stop here. The keys will be shown.
  122. return;
  123. }
  124. }
  125. $list_i18n_files = array_values(array_diff(
  126. scandir($lang_path) ?: [],
  127. ['..', '.']
  128. ));
  129. // Each file basename correspond to a top-level i18n key. For each of
  130. // these keys we store the file pathname and mark translations must be
  131. // reloaded (by setting $translates[$i18n_key] to null).
  132. foreach ($list_i18n_files as $i18n_filename) {
  133. $i18n_key = basename($i18n_filename, '.php');
  134. if (!isset(self::$lang_files[$i18n_key])) {
  135. self::$lang_files[$i18n_key] = [];
  136. }
  137. self::$lang_files[$i18n_key][] = $lang_path . '/' . $i18n_filename;
  138. self::$translates[$i18n_key] = null;
  139. }
  140. }
  141. /**
  142. * Load the files associated to $key into $translates.
  143. * @param string $key the top level i18n key we want to load.
  144. */
  145. private static function loadKey(string $key): bool {
  146. // The top level key is not in $lang_files, it means it does not exist!
  147. if (!isset(self::$lang_files[$key])) {
  148. Minz_Log::debug($key . ' is not a valid top level key');
  149. return false;
  150. }
  151. self::$translates[$key] = [];
  152. foreach (self::$lang_files[$key] as $lang_pathname) {
  153. $i18n_array = include($lang_pathname);
  154. if (!is_array($i18n_array)) {
  155. Minz_Log::warning('`' . $lang_pathname . '` does not contain a PHP array');
  156. continue;
  157. }
  158. // We must avoid to erase previous data so we just override them if
  159. // needed.
  160. self::$translates[$key] = array_replace_recursive(
  161. self::$translates[$key], $i18n_array
  162. );
  163. }
  164. return true;
  165. }
  166. /**
  167. * Translate a key into its corresponding value based on selected language.
  168. * @param string $key the key to translate.
  169. * @param bool|float|int|string ...$args additional parameters for variable keys.
  170. * @return string value corresponding to the key.
  171. * If no value is found, return the key itself.
  172. */
  173. public static function t(string $key, ...$args): string {
  174. $group = explode('.', $key);
  175. if (count($group) < 2) {
  176. Minz_Log::debug($key . ' is not in a valid format');
  177. $top_level = 'gen';
  178. } else {
  179. $top_level = array_shift($group) ?? '';
  180. }
  181. // If $translates[$top_level] is null it means we have to load the
  182. // corresponding files.
  183. if (empty(self::$translates[$top_level])) {
  184. $res = self::loadKey($top_level);
  185. if (!$res) {
  186. return $key;
  187. }
  188. }
  189. // Go through the i18n keys to get the correct translation value.
  190. $translates = self::$translates[$top_level];
  191. if (!is_array($translates)) {
  192. $translates = [];
  193. }
  194. $size_group = count($group);
  195. $level_processed = 0;
  196. $translation_value = $key;
  197. foreach ($group as $i18n_level) {
  198. if (!is_array($translates)) {
  199. continue; // Not needed. To help PHPStan
  200. }
  201. $level_processed++;
  202. if (!isset($translates[$i18n_level])) {
  203. Minz_Log::debug($key . ' is not a valid key');
  204. return $key;
  205. }
  206. if ($level_processed < $size_group) {
  207. $translates = $translates[$i18n_level];
  208. } else {
  209. $translation_value = $translates[$i18n_level];
  210. }
  211. }
  212. if (!is_string($translation_value)) {
  213. $translation_value = is_array($translation_value) ? ($translation_value['_'] ?? null) : null;
  214. if (!is_string($translation_value)) {
  215. Minz_Log::debug($key . ' is not a valid key');
  216. return $key;
  217. }
  218. }
  219. // Get the facultative arguments to replace i18n variables.
  220. return empty($args) ? $translation_value : vsprintf($translation_value, $args);
  221. }
  222. /**
  223. * Return the current language.
  224. */
  225. public static function language(): string {
  226. return self::$lang_name;
  227. }
  228. }
  229. /**
  230. * Alias for Minz_Translate::t()
  231. */
  232. function _t(string $key, bool|float|int|string ...$args): string {
  233. return Minz_Translate::t($key, ...$args);
  234. }