Translate.php 7.4 KB

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