Translate.php 6.9 KB

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