Translate.php 7.0 KB

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