IcuResFileLoader.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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\Translation\Loader;
  11. use Symfony\Component\Config\Resource\DirectoryResource;
  12. use Symfony\Component\Translation\Exception\InvalidResourceException;
  13. use Symfony\Component\Translation\Exception\NotFoundResourceException;
  14. use Symfony\Component\Translation\MessageCatalogue;
  15. /**
  16. * IcuResFileLoader loads translations from a resource bundle.
  17. *
  18. * @author stealth35
  19. */
  20. class IcuResFileLoader implements LoaderInterface
  21. {
  22. public function load(mixed $resource, string $locale, string $domain = 'messages'): MessageCatalogue
  23. {
  24. if (!stream_is_local($resource)) {
  25. throw new InvalidResourceException(sprintf('This is not a local file "%s".', $resource));
  26. }
  27. if (!is_dir($resource)) {
  28. throw new NotFoundResourceException(sprintf('File "%s" not found.', $resource));
  29. }
  30. try {
  31. $rb = new \ResourceBundle($locale, $resource);
  32. } catch (\Exception) {
  33. $rb = null;
  34. }
  35. if (!$rb) {
  36. throw new InvalidResourceException(sprintf('Cannot load resource "%s".', $resource));
  37. } elseif (intl_is_failure($rb->getErrorCode())) {
  38. throw new InvalidResourceException($rb->getErrorMessage(), $rb->getErrorCode());
  39. }
  40. $messages = $this->flatten($rb);
  41. $catalogue = new MessageCatalogue($locale);
  42. $catalogue->add($messages, $domain);
  43. if (class_exists(DirectoryResource::class)) {
  44. $catalogue->addResource(new DirectoryResource($resource));
  45. }
  46. return $catalogue;
  47. }
  48. /**
  49. * Flattens an ResourceBundle.
  50. *
  51. * The scheme used is:
  52. * key { key2 { key3 { "value" } } }
  53. * Becomes:
  54. * 'key.key2.key3' => 'value'
  55. *
  56. * This function takes an array by reference and will modify it
  57. *
  58. * @param \ResourceBundle $rb The ResourceBundle that will be flattened
  59. * @param array $messages Used internally for recursive calls
  60. * @param string|null $path Current path being parsed, used internally for recursive calls
  61. */
  62. protected function flatten(\ResourceBundle $rb, array &$messages = [], ?string $path = null): array
  63. {
  64. foreach ($rb as $key => $value) {
  65. $nodePath = $path ? $path.'.'.$key : $key;
  66. if ($value instanceof \ResourceBundle) {
  67. $this->flatten($value, $messages, $nodePath);
  68. } else {
  69. $messages[$nodePath] = $value;
  70. }
  71. }
  72. return $messages;
  73. }
  74. }