ArrayLoader.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. public function load(mixed $resource, string $locale, string $domain = 'messages'): MessageCatalogue
  20. {
  21. $resource = $this->flatten($resource);
  22. $catalogue = new MessageCatalogue($locale);
  23. $catalogue->add($resource, $domain);
  24. return $catalogue;
  25. }
  26. /**
  27. * Flattens an nested array of translations.
  28. *
  29. * The scheme used is:
  30. * 'key' => ['key2' => ['key3' => 'value']]
  31. * Becomes:
  32. * 'key.key2.key3' => 'value'
  33. */
  34. private function flatten(array $messages): array
  35. {
  36. $result = [];
  37. foreach ($messages as $key => $value) {
  38. if (\is_array($value)) {
  39. foreach ($this->flatten($value) as $k => $v) {
  40. if (null !== $v) {
  41. $result[$key.'.'.$k] = $v;
  42. }
  43. }
  44. } elseif (null !== $value) {
  45. $result[$key] = $value;
  46. }
  47. }
  48. return $result;
  49. }
  50. }