ArrayLoader.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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, $locale, $domain = 'messages')
  23. {
  24. $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' => array('key2' => array('key3' => 'value'))
  34. * Becomes:
  35. * 'key.key2.key3' => 'value'
  36. *
  37. * This function takes an array by reference and will modify it
  38. *
  39. * @param array &$messages The array that will be flattened
  40. * @param array $subnode Current subnode being parsed, used internally for recursive calls
  41. * @param string $path Current path being parsed, used internally for recursive calls
  42. */
  43. private function flatten(array &$messages, array $subnode = null, $path = null)
  44. {
  45. if (null === $subnode) {
  46. $subnode = &$messages;
  47. }
  48. foreach ($subnode as $key => $value) {
  49. if (is_array($value)) {
  50. $nodePath = $path ? $path.'.'.$key : $key;
  51. $this->flatten($messages, $value, $nodePath);
  52. if (null === $path) {
  53. unset($messages[$key]);
  54. }
  55. } elseif (null !== $path) {
  56. $messages[$path.'.'.$key] = $value;
  57. }
  58. }
  59. }
  60. }