ArrayLoader.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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\Translation\MessageCatalogue;
  12. /**
  13. * ArrayLoader loads translations from a PHP array.
  14. *
  15. * @author Fabien Potencier <fabien@symfony.com>
  16. */
  17. class ArrayLoader implements LoaderInterface
  18. {
  19. /**
  20. * {@inheritdoc}
  21. */
  22. public function load($resource, string $locale, string $domain = 'messages')
  23. {
  24. $resource = $this->flatten($resource);
  25. $catalogue = new MessageCatalogue($locale);
  26. $catalogue->add($resource, $domain);
  27. return $catalogue;
  28. }
  29. /**
  30. * Flattens an nested array of translations.
  31. *
  32. * The scheme used is:
  33. * 'key' => ['key2' => ['key3' => 'value']]
  34. * Becomes:
  35. * 'key.key2.key3' => 'value'
  36. */
  37. private function flatten(array $messages): array
  38. {
  39. $result = [];
  40. foreach ($messages as $key => $value) {
  41. if (\is_array($value)) {
  42. foreach ($this->flatten($value) as $k => $v) {
  43. $result[$key.'.'.$k] = $v;
  44. }
  45. } else {
  46. $result[$key] = $value;
  47. }
  48. }
  49. return $result;
  50. }
  51. }