ResourceBundle.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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;
  11. use Symfony\Component\Intl\Data\Bundle\Reader\BufferedBundleReader;
  12. use Symfony\Component\Intl\Data\Bundle\Reader\BundleEntryReader;
  13. use Symfony\Component\Intl\Data\Bundle\Reader\BundleEntryReaderInterface;
  14. use Symfony\Component\Intl\Data\Bundle\Reader\JsonBundleReader;
  15. /**
  16. * @author Roland Franssen <franssen.roland@gmail.com>
  17. *
  18. * @internal
  19. */
  20. abstract class ResourceBundle
  21. {
  22. private static $entryReader;
  23. abstract protected static function getPath(): string;
  24. /**
  25. * Reads an entry from a resource bundle.
  26. *
  27. * @see BundleEntryReaderInterface::readEntry()
  28. *
  29. * @param string[] $indices The indices to read from the bundle
  30. * @param string $locale The locale to read
  31. * @param bool $fallback Whether to merge the value with the value from
  32. * the fallback locale (e.g. "en" for "en_GB").
  33. * Only applicable if the result is multivalued
  34. * (i.e. array or \ArrayAccess) or cannot be found
  35. * in the requested locale.
  36. *
  37. * @return mixed returns an array or {@link \ArrayAccess} instance for
  38. * complex data and a scalar value for simple data
  39. */
  40. final protected static function readEntry(array $indices, string $locale = null, bool $fallback = true)
  41. {
  42. if (null === self::$entryReader) {
  43. self::$entryReader = new BundleEntryReader(new BufferedBundleReader(
  44. new JsonBundleReader(),
  45. Intl::BUFFER_SIZE
  46. ));
  47. $localeAliases = self::$entryReader->readEntry(Intl::getDataDirectory().'/'.Intl::LOCALE_DIR, 'meta', ['Aliases']);
  48. self::$entryReader->setLocaleAliases($localeAliases instanceof \Traversable ? iterator_to_array($localeAliases) : $localeAliases);
  49. }
  50. return self::$entryReader->readEntry(static::getPath(), $locale ?? \Locale::getDefault(), $indices, $fallback);
  51. }
  52. final protected static function asort(iterable $list, string $locale = null): array
  53. {
  54. if ($list instanceof \Traversable) {
  55. $list = iterator_to_array($list);
  56. }
  57. $collator = new \Collator($locale ?? \Locale::getDefault());
  58. $collator->asort($list);
  59. return $list;
  60. }
  61. private function __construct()
  62. {
  63. }
  64. }