I18nData.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. <?php
  2. declare(strict_types=1);
  3. class I18nData {
  4. /** @var string */
  5. public const REFERENCE_LANGUAGE = 'en';
  6. /** @param array<string,array<string,array<string,I18nValue>>> $data */
  7. public function __construct(private array $data) {
  8. $this->addMissingKeysFromReference();
  9. $this->removeExtraKeysFromOtherLanguages();
  10. $this->processValueStates();
  11. }
  12. /**
  13. * @return array<string,array<string,array<string,I18nValue>>>
  14. */
  15. public function getData(): array {
  16. return $this->data;
  17. }
  18. private function addMissingKeysFromReference(): void {
  19. $reference = $this->getReferenceLanguage();
  20. $languages = $this->getNonReferenceLanguages();
  21. foreach ($reference as $file => $refValues) {
  22. foreach ($refValues as $key => $refValue) {
  23. foreach ($languages as $language) {
  24. if (!array_key_exists($file, $this->data[$language]) || !array_key_exists($key, $this->data[$language][$file])) {
  25. $this->data[$language][$file][$key] = clone $refValue;
  26. }
  27. $value = $this->data[$language][$file][$key];
  28. if ($refValue->equal($value) && !$value->isIgnore()) {
  29. $value->markAsTodo();
  30. }
  31. }
  32. }
  33. }
  34. }
  35. private function removeExtraKeysFromOtherLanguages(): void {
  36. $reference = $this->getReferenceLanguage();
  37. foreach ($this->getNonReferenceLanguages() as $language) {
  38. foreach ($this->getLanguage($language) as $file => $values) {
  39. foreach ($values as $key => $value) {
  40. if (!array_key_exists($key, $reference[$file])) {
  41. unset($this->data[$language][$file][$key]);
  42. }
  43. }
  44. }
  45. }
  46. }
  47. private function processValueStates(): void {
  48. $reference = $this->getReferenceLanguage();
  49. $languages = $this->getNonReferenceLanguages();
  50. foreach ($reference as $file => $refValues) {
  51. foreach ($refValues as $key => $refValue) {
  52. foreach ($languages as $language) {
  53. $value = $this->data[$language][$file][$key];
  54. if ($refValue->equal($value) && !$value->isIgnore()) {
  55. $value->markAsTodo();
  56. continue;
  57. }
  58. if (!$refValue->equal($value) && $value->isTodo()) {
  59. $value->markAsDirty();
  60. continue;
  61. }
  62. }
  63. }
  64. }
  65. }
  66. /**
  67. * Return the available languages
  68. * @return list<string>
  69. */
  70. public function getAvailableLanguages(): array {
  71. $languages = array_keys($this->data);
  72. sort($languages);
  73. return $languages;
  74. }
  75. /**
  76. * Return all available languages without the reference language
  77. * @return list<string>
  78. */
  79. private function getNonReferenceLanguages(): array {
  80. return array_values(array_filter(array_keys($this->data),
  81. static fn(string $value) => static::REFERENCE_LANGUAGE !== $value));
  82. }
  83. /**
  84. * Add a new language. It’s a copy of the reference language.
  85. * @throws Exception
  86. */
  87. public function addLanguage(string $language, ?string $reference = null): void {
  88. if (array_key_exists($language, $this->data)) {
  89. throw new Exception('The selected language already exists.');
  90. }
  91. if (!is_string($reference) || !array_key_exists($reference, $this->data)) {
  92. $reference = static::REFERENCE_LANGUAGE;
  93. }
  94. $this->data[$language] = $this->data[$reference];
  95. }
  96. /**
  97. * Check if the key is known.
  98. */
  99. public function isKnown(string $key): bool {
  100. return $this->exists($key) &&
  101. array_key_exists($key, $this->data[static::REFERENCE_LANGUAGE][$this->getFilenamePrefix($key)]);
  102. }
  103. /**
  104. * Check if the file exists
  105. */
  106. public function exists(string $file): bool {
  107. return array_key_exists($this->getFilenamePrefix($file), $this->data[static::REFERENCE_LANGUAGE]);
  108. }
  109. /**
  110. * Return the parent key for a specified key.
  111. * To get the parent key, you need to remove the last section of the key. Each
  112. * is separated into sections. The parent of a section is the concatenation of
  113. * all sections before the selected key. For instance, if the key is 'a.b.c.d.e',
  114. * the parent key is 'a.b.c.d'.
  115. */
  116. private function getParentKey(string $key): string {
  117. return substr($key, 0, strrpos($key, '.') ?: null);
  118. }
  119. /**
  120. * Return the siblings for a specified key.
  121. * To get the siblings, we need to find all matches with the parent.
  122. *
  123. * @return list<string>
  124. */
  125. private function getSiblings(string $key): array {
  126. if (!array_key_exists($this->getFilenamePrefix($key), $this->data[static::REFERENCE_LANGUAGE])) {
  127. return [];
  128. }
  129. $keys = array_keys($this->data[static::REFERENCE_LANGUAGE][$this->getFilenamePrefix($key)]);
  130. $parent = $this->getParentKey($key);
  131. return array_values(array_filter($keys, static fn(string $element) => str_contains($element, $parent)));
  132. }
  133. /**
  134. * Check if the key is an only child.
  135. * To be an only child, there must be only one sibling and that sibling must
  136. * be the empty sibling. The empty sibling is the parent.
  137. */
  138. private function isOnlyChild(string $key): bool {
  139. $siblings = $this->getSiblings($key);
  140. if (1 !== count($siblings)) {
  141. return false;
  142. }
  143. return '_' === $siblings[0][-1];
  144. }
  145. /**
  146. * Return the parent key as an empty sibling.
  147. * When a key has children, it cannot have its value directly. The value
  148. * needs to be attached to an empty sibling represented by "_".
  149. */
  150. private function getEmptySibling(string $key): string {
  151. return "{$key}._";
  152. }
  153. /**
  154. * Check if a key is a parent key.
  155. * To be a parent key, there must be at least one key starting with the key
  156. * under test. Of course, it cannot be itself.
  157. */
  158. private function isParent(string $key): bool {
  159. if (!array_key_exists($this->getFilenamePrefix($key), $this->data[static::REFERENCE_LANGUAGE])) {
  160. return false;
  161. }
  162. $keys = array_keys($this->data[static::REFERENCE_LANGUAGE][$this->getFilenamePrefix($key)]);
  163. $children = array_values(array_filter($keys, static function (string $element) use ($key) {
  164. if ($element === $key) {
  165. return false;
  166. }
  167. return str_contains($element, $key);
  168. }));
  169. return count($children) !== 0;
  170. }
  171. /**
  172. * Add a new translation file to all languages
  173. * @throws Exception
  174. */
  175. public function addFile(string $file): void {
  176. $file = strtolower($file);
  177. if (!str_ends_with($file, '.php')) {
  178. throw new Exception('The selected file name is not supported.');
  179. }
  180. if ($this->exists($file)) {
  181. throw new Exception('The selected file exists already.');
  182. }
  183. foreach ($this->getAvailableLanguages() as $language) {
  184. $this->data[$language][$this->getFilenamePrefix($file)] = [];
  185. }
  186. }
  187. /**
  188. * Add a new key to all languages.
  189. * @throws Exception
  190. */
  191. public function addKey(string $key, string $value): void {
  192. if ($this->isParent($key)) {
  193. $key = $this->getEmptySibling($key);
  194. }
  195. if ($this->isKnown($key)) {
  196. throw new Exception('The selected key already exists.');
  197. }
  198. $parentKey = $this->getParentKey($key);
  199. if ($this->isKnown($parentKey)) {
  200. // The parent key exists, that means that we need to convert it to an array.
  201. // To create an array, we need to change the key by appending an empty section.
  202. foreach ($this->getAvailableLanguages() as $language) {
  203. $parentValue = $this->data[$language][$this->getFilenamePrefix($parentKey)][$parentKey];
  204. $this->data[$language][$this->getFilenamePrefix($this->getEmptySibling($parentKey))][$this->getEmptySibling($parentKey)] =
  205. new I18nValue($parentValue);
  206. }
  207. }
  208. $value = new I18nValue($value);
  209. $value->markAsTodo();
  210. foreach ($this->getAvailableLanguages() as $language) {
  211. if (!array_key_exists($key, $this->data[$language][$this->getFilenamePrefix($key)])) {
  212. $this->data[$language][$this->getFilenamePrefix($key)][$key] = $value;
  213. }
  214. }
  215. if ($this->isKnown($parentKey)) {
  216. $this->removeKey($parentKey);
  217. }
  218. }
  219. /**
  220. * Move an existing key into a new location
  221. * @throws Exception
  222. */
  223. public function moveKey(string $key, string $newKey): void {
  224. if (!$this->isKnown($key) && !$this->isKnown($this->getEmptySibling($key))) {
  225. throw new Exception('The selected key does not exist');
  226. }
  227. if ($this->isKnown($newKey)) {
  228. throw new Exception('Cannot move key to a location that already exists.');
  229. }
  230. $keyPrefix = $this->isParent($key) ? $key . '.' : $key;
  231. foreach ($this->getAvailableLanguages() as $language) {
  232. foreach ($this->data[$language][$this->getFilenamePrefix($key)] as $k => $v) {
  233. if (str_starts_with($k, $keyPrefix)) {
  234. $this->data[$language][$this->getFilenamePrefix($newKey)][str_replace($key, $newKey, $k)] = $v;
  235. unset($this->data[$language][$this->getFilenamePrefix($key)][$k]);
  236. }
  237. }
  238. }
  239. }
  240. /**
  241. * Add a value for a key for the selected language.
  242. *
  243. * @throws Exception
  244. */
  245. public function addValue(string $key, string $value, string $language): void {
  246. if (!in_array($language, $this->getAvailableLanguages(), true)) {
  247. throw new Exception('The selected language does not exist.');
  248. }
  249. if (!array_key_exists($this->getFilenamePrefix($key), $this->data[static::REFERENCE_LANGUAGE]) ||
  250. !array_key_exists($key, $this->data[static::REFERENCE_LANGUAGE][$this->getFilenamePrefix($key)])) {
  251. throw new Exception('The selected key does not exist for the selected language.');
  252. }
  253. $value = new I18nValue($value);
  254. if (static::REFERENCE_LANGUAGE === $language) {
  255. $previousValue = $this->data[static::REFERENCE_LANGUAGE][$this->getFilenamePrefix($key)][$key];
  256. foreach ($this->getAvailableLanguages() as $lang) {
  257. $currentValue = $this->data[$lang][$this->getFilenamePrefix($key)][$key];
  258. if ($currentValue->equal($previousValue)) {
  259. $this->data[$lang][$this->getFilenamePrefix($key)][$key] = $value;
  260. }
  261. }
  262. } else {
  263. $this->data[$language][$this->getFilenamePrefix($key)][$key] = $value;
  264. }
  265. }
  266. /**
  267. * Remove a key in all languages
  268. */
  269. public function removeKey(string $key): void {
  270. if (!$this->isKnown($key) && !$this->isKnown($this->getEmptySibling($key))) {
  271. throw new Exception('The selected key does not exist.');
  272. }
  273. if (!$this->isKnown($key)) {
  274. // The key has children, it needs to be appended with an empty section.
  275. $key = $this->getEmptySibling($key);
  276. }
  277. foreach ($this->getAvailableLanguages() as $language) {
  278. if (array_key_exists($key, $this->data[$language][$this->getFilenamePrefix($key)])) {
  279. unset($this->data[$language][$this->getFilenamePrefix($key)][$key]);
  280. }
  281. }
  282. if ($this->isOnlyChild($key)) {
  283. $parentKey = $this->getParentKey($key);
  284. foreach ($this->getAvailableLanguages() as $language) {
  285. $parentValue = $this->data[$language][$this->getFilenamePrefix($this->getEmptySibling($parentKey))][$this->getEmptySibling($parentKey)];
  286. $this->data[$language][$this->getFilenamePrefix($parentKey)][$parentKey] = $parentValue;
  287. }
  288. $this->removeKey($this->getEmptySibling($parentKey));
  289. }
  290. }
  291. /**
  292. * Ignore a key from a language, or revert an existing ignore on a key.
  293. */
  294. public function ignore(string $key, string $language, bool $revert = false): void {
  295. $value = $this->data[$language][$this->getFilenamePrefix($key)][$key];
  296. if ($revert) {
  297. $value->unmarkAsIgnore();
  298. } else {
  299. $value->markAsIgnore();
  300. }
  301. }
  302. /**
  303. * Ignore all unmodified keys from a language, or revert all existing ignores on unmodified keys.
  304. */
  305. public function ignore_unmodified(string $language, bool $revert = false): void {
  306. $my_language = $this->getLanguage($language);
  307. foreach ($this->getReferenceLanguage() as $file => $ref_language) {
  308. foreach ($ref_language as $key => $ref_value) {
  309. if (array_key_exists($key, $my_language[$file])) {
  310. if ($ref_value->equal($my_language[$file][$key])) {
  311. $this->ignore($key, $language, $revert);
  312. }
  313. }
  314. }
  315. }
  316. }
  317. /**
  318. * @return array<string,array<string,I18nValue>>
  319. */
  320. public function getLanguage(string $language): array {
  321. return $this->data[$language];
  322. }
  323. /**
  324. * @return array<string,array<string,I18nValue>>
  325. */
  326. public function getReferenceLanguage(): array {
  327. return $this->getLanguage(static::REFERENCE_LANGUAGE);
  328. }
  329. private function getFilenamePrefix(string $key): string {
  330. return preg_replace('/\..*/', '.php', $key) ?? '';
  331. }
  332. }