I18nFile.php 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. <?php
  2. declare(strict_types=1);
  3. require_once __DIR__ . '/I18nValue.php';
  4. class I18nFile {
  5. /**
  6. * @param array<mixed,mixed> $array
  7. * @phpstan-assert-if-true array<int|string,string|array<mixed>> $array
  8. */
  9. public static function is_array_recursive_string(array $array): bool {
  10. foreach ($array as $value) {
  11. if (!is_string($value) && !(is_array($value) && self::is_array_recursive_string($value))) {
  12. return false;
  13. }
  14. }
  15. return true;
  16. }
  17. /**
  18. * @return array<string,array<string,array<string,I18nValue>>>
  19. */
  20. public function load(): array {
  21. $i18n = [];
  22. $dirs = new DirectoryIterator(I18N_PATH);
  23. foreach ($dirs as $dir) {
  24. if ($dir->isDot()) {
  25. continue;
  26. }
  27. $files = new DirectoryIterator($dir->getPathname());
  28. foreach ($files as $file) {
  29. if (!$file->isFile()) {
  30. continue;
  31. }
  32. if ($file->getFilename() === 'plurals.php') {
  33. continue;
  34. }
  35. $i18n[$dir->getFilename()][$file->getFilename()] = $this->flatten($this->process($file->getPathname()), $file->getBasename('.php'));
  36. }
  37. }
  38. return $i18n;
  39. }
  40. /**
  41. * @param array<string,array<string,array<string,I18nValue>>> $i18n
  42. */
  43. public function dump(array $i18n): void {
  44. foreach ($i18n as $language => $file) {
  45. $dir = I18N_PATH . DIRECTORY_SEPARATOR . $language;
  46. if (!file_exists($dir)) {
  47. mkdir($dir, 0770, true);
  48. }
  49. foreach ($file as $name => $content) {
  50. $filename = $dir . DIRECTORY_SEPARATOR . $name;
  51. $reference = $language === 'en' ? [] : ($i18n['en'][$name] ?? []);
  52. file_put_contents($filename, $this->format($content, $reference));
  53. }
  54. }
  55. }
  56. /**
  57. * Process the content of an i18n file
  58. * @return array<int|string,string|array<mixed>>
  59. */
  60. private function process(string $filename): array {
  61. $fileContent = file_get_contents($filename);
  62. if (!is_string($fileContent)) {
  63. return [];
  64. }
  65. $content = str_replace('<?php', '', $fileContent);
  66. $content = preg_replace([
  67. "#',\s*//\s*TODO.*#i",
  68. "#',\s*//\s*DIRTY.*#i",
  69. "#',\s*//\s*IGNORE.*#i",
  70. ], [
  71. ' -> todo\',',
  72. ' -> dirty\',',
  73. ' -> ignore\',',
  74. ], $content);
  75. try {
  76. $content = eval($content);
  77. } catch (ParseError $ex) {
  78. if (defined('STDERR')) {
  79. fwrite(STDERR, "Error while processing: $filename\n");
  80. fwrite(STDERR, $ex->getMessage());
  81. }
  82. die(1);
  83. }
  84. if (is_array($content) && self::is_array_recursive_string($content)) {
  85. return $content;
  86. }
  87. return [];
  88. }
  89. /**
  90. * Flatten an array of translation
  91. *
  92. * @param array<int|string,I18nValue|string|array<mixed>|mixed> $translation
  93. * @return array<string,I18nValue>
  94. */
  95. private function flatten(array $translation, string $prefix = ''): array {
  96. $a = [];
  97. if ('' !== $prefix) {
  98. $prefix .= '.';
  99. }
  100. foreach ($translation as $key => $value) {
  101. $key = (string)$key;
  102. if (is_array($value) && self::is_array_recursive_string($value)) {
  103. $a += $this->flatten($value, $prefix . $key);
  104. } elseif (is_string($value) || $value instanceof I18nValue) {
  105. $a[$prefix . $key] = new I18nValue($value);
  106. }
  107. }
  108. return $a;
  109. }
  110. /**
  111. * Unflatten an array of translation
  112. *
  113. * The first key is dropped since it represents the filename and we have
  114. * no use of it.
  115. *
  116. * @param array<string,I18nValue> $translation
  117. * @return array<int|string,mixed>
  118. */
  119. private function unflatten(array $translation): array {
  120. $a = [];
  121. ksort($translation, SORT_NATURAL);
  122. foreach ($translation as $compoundKey => $value) {
  123. $keys = explode('.', $compoundKey);
  124. array_shift($keys);
  125. $current =& $a;
  126. $lastIndex = count($keys) - 1;
  127. foreach ($keys as $index => $key) {
  128. $normalisedKey = ctype_digit($key) ? (int)$key : $key;
  129. if ($index === $lastIndex) {
  130. $current[$normalisedKey] = $value->__toString();
  131. if ($value->isDirty()) {
  132. // Carry the key through var_export, including when several keys share the same translation.
  133. $current[$normalisedKey] .= ':' . base64_encode($compoundKey);
  134. }
  135. continue;
  136. }
  137. if (!isset($current[$normalisedKey]) || !is_array($current[$normalisedKey])) {
  138. $current[$normalisedKey] = [];
  139. }
  140. $current =& $current[$normalisedKey];
  141. }
  142. unset($current);
  143. }
  144. return $a;
  145. }
  146. /**
  147. * Format an array of translation
  148. *
  149. * It takes an array of translation and format it to be dumped in a
  150. * translation file. The array is first converted to a string then some
  151. * formatting regexes are applied to match the original content.
  152. *
  153. * @param array<string,I18nValue> $translation
  154. * @param array<string,I18nValue> $reference
  155. */
  156. private function format(array $translation, array $reference = []): string {
  157. $translationKeys = array_fill_keys(array_keys($translation), true);
  158. $translation = var_export($this->unflatten($translation), true);
  159. $patterns = [
  160. '/ -> todo\',/',
  161. '/ -> ignore\',/',
  162. '/array \(/',
  163. '/=>\s*array/',
  164. '/(\w) {2}/',
  165. '/ {2}/',
  166. ];
  167. $replacements = [
  168. "',\t// TODO", // Double quoting is mandatory to have a tab instead of the \t string
  169. "',\t// IGNORE", // Double quoting is mandatory to have a tab instead of the \t string
  170. 'array(',
  171. '=> array',
  172. '$1 ',
  173. "\t", // Double quoting is mandatory to have a tab instead of the \t string
  174. ];
  175. $translation = preg_replace($patterns, $replacements, $translation);
  176. $translation = preg_replace_callback('/ -> dirty:([A-Za-z0-9+\/=]+)\',/', static function (array $matches) use ($reference, $translationKeys): string {
  177. $key = base64_decode($matches[1], true);
  178. $original = $key === false ? null : ($reference[$key] ?? null);
  179. if ($original === null && $key !== false && preg_match('/^(.+)\.\d+$/', $key, $parts) === 1) {
  180. $original = $reference[$parts[1] . '.1'] ?? $reference[$parts[1] . '.0'] ?? null;
  181. }
  182. if ($original === null) {
  183. return "',\t// DIRTY";
  184. }
  185. $comment = $original->getValue();
  186. if ($key !== false && preg_match('/^(.+)\.0$/', $key, $parts) === 1
  187. && !isset($translationKeys[$parts[1] . '.1']) && isset($reference[$key], $reference[$parts[1] . '.1'])) {
  188. $comment = 'Singular: ' . $comment . ' | Plural: ' . $reference[$parts[1] . '.1']->getValue();
  189. }
  190. // Keep the reference inside its line comment, including when it contains a PHP closing tag.
  191. $comment = trim(preg_replace('/\s+/', ' ', $comment) ?? '');
  192. $comment = str_replace('?>', '? >', $comment);
  193. return "',\t// DIRTY" . ($comment === '' ? '' : ' - ' . $comment);
  194. }, $translation ?? '');
  195. return <<<PHP
  196. <?php
  197. /******************************************************************************
  198. * Each entry of that file can be associated with a comment to indicate its *
  199. * state. When there is no comment, it means the entry is fully translated. *
  200. * The recognized comments are (comment matching is case-insensitive): *
  201. * + TODO: the entry has never been translated. *
  202. * + DIRTY: the entry has been translated but needs to be updated. *
  203. * + IGNORE: the entry does not need to be translated. *
  204. * When a comment is not recognized, it is discarded. *
  205. ******************************************************************************/
  206. return {$translation};
  207. PHP;
  208. }
  209. }