LocaleScanner.php 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Intl\Data\Util;
  11. /**
  12. * Scans a directory with data files for locales.
  13. *
  14. * The name of each file with the extension ".txt" is considered, if it "looks"
  15. * like a locale:
  16. *
  17. * - the name must start with two letters;
  18. * - the two letters may optionally be followed by an underscore and any
  19. * sequence of other symbols.
  20. *
  21. * For example, "de" and "de_DE" are considered to be locales. "root" and "meta"
  22. * are not.
  23. *
  24. * @author Bernhard Schussek <bschussek@gmail.com>
  25. *
  26. * @internal
  27. */
  28. class LocaleScanner
  29. {
  30. /**
  31. * Returns all locales found in the given directory.
  32. *
  33. * @param string $sourceDir The directory with ICU files
  34. *
  35. * @return array An array of locales. The result also contains locales that
  36. * are in fact just aliases for other locales. Use
  37. * {@link scanAliases()} to determine which of the locales
  38. * are aliases
  39. */
  40. public function scanLocales($sourceDir)
  41. {
  42. $locales = glob($sourceDir.'/*.txt');
  43. // Remove file extension and sort
  44. array_walk($locales, function (&$locale) { $locale = basename($locale, '.txt'); });
  45. // Remove non-locales
  46. $locales = array_filter($locales, function ($locale) {
  47. return preg_match('/^[a-z]{2}(_.+)?$/', $locale);
  48. });
  49. sort($locales);
  50. return $locales;
  51. }
  52. /**
  53. * Returns all locale aliases found in the given directory.
  54. *
  55. * @param string $sourceDir The directory with ICU files
  56. *
  57. * @return array An array with the locale aliases as keys and the aliased
  58. * locales as values
  59. */
  60. public function scanAliases($sourceDir)
  61. {
  62. $locales = $this->scanLocales($sourceDir);
  63. $aliases = array();
  64. // Delete locales that are no aliases
  65. foreach ($locales as $locale) {
  66. $content = file_get_contents($sourceDir.'/'.$locale.'.txt');
  67. // Aliases contain the text "%%ALIAS" followed by the aliased locale
  68. if (preg_match('/"%%ALIAS"\{"([^"]+)"\}/', $content, $matches)) {
  69. $aliases[$locale] = $matches[1];
  70. }
  71. }
  72. return $aliases;
  73. }
  74. }