I18nIgnoreFile.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. require_once __DIR__ . '/I18nData.php';
  3. require_once __DIR__ . '/I18nFileInterface.php';
  4. class I18nIgnoreFile implements I18nFileInterface {
  5. private $i18nPath;
  6. public function __construct() {
  7. $this->i18nPath = __DIR__ . '/ignore';
  8. }
  9. public function dump(I18nData $i18n) {
  10. foreach ($i18n->getData() as $language => $content) {
  11. $filename = $this->i18nPath . DIRECTORY_SEPARATOR . $language . '.php';
  12. file_put_contents($filename, $this->format($content));
  13. }
  14. }
  15. public function load() {
  16. $i18n = array();
  17. $files = new DirectoryIterator($this->i18nPath);
  18. foreach ($files as $file) {
  19. if (!$file->isFile()) {
  20. continue;
  21. }
  22. $i18n[$file->getBasename('.php')] = (include $file->getPathname());
  23. }
  24. return new I18nData($i18n);
  25. }
  26. /**
  27. * Format an array of translation
  28. *
  29. * It takes an array of translation and format it to be dumped in a
  30. * translation file. The array is first converted to a string then some
  31. * formatting regexes are applied to match the original content.
  32. *
  33. * @param array $translation
  34. * @return string
  35. */
  36. private function format($translation) {
  37. $translation = var_export(($translation), true);
  38. $patterns = array(
  39. '/array \(/',
  40. '/=>\s*array/',
  41. '/ {2}/',
  42. '/\d+ => /',
  43. );
  44. $replacements = array(
  45. 'array(',
  46. '=> array',
  47. "\t", // Double quoting is mandatory to have a tab instead of the \t string
  48. '',
  49. );
  50. $translation = preg_replace($patterns, $replacements, $translation);
  51. // Double quoting is mandatory to have new lines instead of \n strings
  52. return sprintf("<?php\n\nreturn %s;\n", $translation);
  53. }
  54. }