Translate.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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 array<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_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 (self::$lang_name === '' || !is_dir($lang_path)) {
  114. // The lang path does not exist, fallback to English ('en')
  115. $lang_path = $path . '/en';
  116. if (!is_dir($lang_path)) {
  117. // English ('en') i18n files not provided. Stop here. The keys will be shown.
  118. return;
  119. }
  120. }
  121. $list_i18n_files = array_values(array_diff(
  122. scandir($lang_path) ?: [],
  123. ['..', '.']
  124. ));
  125. // Each file basename correspond to a top-level i18n key. For each of
  126. // these keys we store the file pathname and mark translations must be
  127. // reloaded (by setting $translates[$i18n_key] to null).
  128. foreach ($list_i18n_files as $i18n_filename) {
  129. $i18n_key = basename($i18n_filename, '.php');
  130. if (!isset(self::$lang_files[$i18n_key])) {
  131. self::$lang_files[$i18n_key] = [];
  132. }
  133. self::$lang_files[$i18n_key][] = $lang_path . '/' . $i18n_filename;
  134. self::$translates[$i18n_key] = null;
  135. }
  136. }
  137. /**
  138. * Load the files associated to $key into $translates.
  139. * @param string $key the top level i18n key we want to load.
  140. */
  141. private static function loadKey(string $key): bool {
  142. // The top level key is not in $lang_files, it means it does not exist!
  143. if (!isset(self::$lang_files[$key])) {
  144. Minz_Log::debug($key . ' is not a valid top level key');
  145. return false;
  146. }
  147. self::$translates[$key] = [];
  148. foreach (self::$lang_files[$key] as $lang_pathname) {
  149. $i18n_array = include($lang_pathname);
  150. if (!is_array($i18n_array)) {
  151. Minz_Log::warning('`' . $lang_pathname . '` does not contain a PHP array');
  152. continue;
  153. }
  154. // We must avoid to erase previous data so we just override them if
  155. // needed.
  156. self::$translates[$key] = array_replace_recursive(
  157. self::$translates[$key], $i18n_array
  158. );
  159. }
  160. return true;
  161. }
  162. /**
  163. * Translate a key into its corresponding value based on selected language.
  164. * @param string $key the key to translate.
  165. * @param bool|float|int|string ...$args additional parameters for variable keys.
  166. * @return string value corresponding to the key.
  167. * If no value is found, return the key itself.
  168. */
  169. public static function t(string $key, ...$args): string {
  170. $group = explode('.', $key);
  171. if (count($group) < 2) {
  172. Minz_Log::debug($key . ' is not in a valid format');
  173. $top_level = 'gen';
  174. } else {
  175. $top_level = array_shift($group);
  176. }
  177. // If $translates[$top_level] is null it means we have to load the
  178. // corresponding files.
  179. if (empty(self::$translates[$top_level])) {
  180. $res = self::loadKey($top_level);
  181. if (!$res) {
  182. return $key;
  183. }
  184. }
  185. // Go through the i18n keys to get the correct translation value.
  186. $translates = self::$translates[$top_level];
  187. if (!is_array($translates)) {
  188. $translates = [];
  189. }
  190. $size_group = count($group);
  191. $level_processed = 0;
  192. $translation_value = $key;
  193. foreach ($group as $i18n_level) {
  194. $level_processed++;
  195. if (!isset($translates[$i18n_level])) {
  196. Minz_Log::debug($key . ' is not a valid key');
  197. return $key;
  198. }
  199. if ($level_processed < $size_group) {
  200. $translates = $translates[$i18n_level];
  201. } else {
  202. $translation_value = $translates[$i18n_level];
  203. }
  204. }
  205. if (is_array($translation_value)) {
  206. if (isset($translation_value['_'])) {
  207. $translation_value = $translation_value['_'];
  208. } else {
  209. Minz_Log::debug($key . ' is not a valid key');
  210. return $key;
  211. }
  212. }
  213. // Get the facultative arguments to replace i18n variables.
  214. return empty($args) ? $translation_value : vsprintf($translation_value, $args);
  215. }
  216. /**
  217. * Return the current language.
  218. */
  219. public static function language(): string {
  220. return self::$lang_name;
  221. }
  222. }
  223. /**
  224. * Alias for Minz_Translate::t()
  225. */
  226. function _t(string $key, bool|float|int|string ...$args): string {
  227. return Minz_Translate::t($key, ...$args);
  228. }