Translate.php 6.8 KB

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