I18nFile.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. require_once __DIR__ . '/I18nData.php';
  3. class i18nFile {
  4. private $i18nPath;
  5. public function __construct() {
  6. $this->i18nPath = __DIR__ . '/../app/i18n';
  7. }
  8. public function load() {
  9. $dirs = new DirectoryIterator($this->i18nPath);
  10. foreach ($dirs as $dir) {
  11. if ($dir->isDot()) {
  12. continue;
  13. }
  14. $files = new DirectoryIterator($dir->getPathname());
  15. foreach ($files as $file) {
  16. if (!$file->isFile()) {
  17. continue;
  18. }
  19. $i18n[$dir->getFilename()][$file->getFilename()] = $this->flatten(include $file->getPathname(), $file->getBasename('.php'));
  20. }
  21. }
  22. return new I18nData($i18n);
  23. }
  24. public function dump(I18nData $i18n) {
  25. foreach ($i18n->getData() as $language => $file) {
  26. $dir = $this->i18nPath . DIRECTORY_SEPARATOR . $language;
  27. if (!file_exists($dir)) {
  28. mkdir($dir);
  29. }
  30. foreach ($file as $name => $content) {
  31. $filename = $dir . DIRECTORY_SEPARATOR . $name;
  32. $fullContent = var_export($this->unflatten($content), true);
  33. file_put_contents($filename, sprintf('<?php return %s;', $fullContent));
  34. }
  35. }
  36. }
  37. /**
  38. * Flatten an array of translation
  39. *
  40. * @param array $translation
  41. * @param string $prefix
  42. * @return array
  43. */
  44. private function flatten($translation, $prefix = '') {
  45. $a = array();
  46. if ('' !== $prefix) {
  47. $prefix .= '.';
  48. }
  49. foreach ($translation as $key => $value) {
  50. if (is_array($value)) {
  51. $a += $this->flatten($value, $prefix . $key);
  52. } else {
  53. $a[$prefix . $key] = $value;
  54. }
  55. }
  56. return $a;
  57. }
  58. /**
  59. * Unflatten an array of translation
  60. *
  61. * The first key is dropped since it represents the filename and we have
  62. * no use of it.
  63. *
  64. * @param array $translation
  65. * @return array
  66. */
  67. private function unflatten($translation) {
  68. $a = array();
  69. ksort($translation);
  70. foreach ($translation as $compoundKey => $value) {
  71. $keys = explode('.', $compoundKey);
  72. array_shift($keys);
  73. eval("\$a['" . implode("']['", $keys) . "'] = '" . $value . "';");
  74. }
  75. return $a;
  76. }
  77. }