ArrayLoader.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. * @api
  18. */
  19. class ArrayLoader implements LoaderInterface
  20. {
  21. /**
  22. * {@inheritdoc}
  23. *
  24. * @api
  25. */
  26. public function load($resource, $locale, $domain = 'messages')
  27. {
  28. $this->flatten($resource);
  29. $catalogue = new MessageCatalogue($locale);
  30. $catalogue->add($resource, $domain);
  31. return $catalogue;
  32. }
  33. /**
  34. * Flattens an nested array of translations
  35. *
  36. * The scheme used is:
  37. * 'key' => array('key2' => array('key3' => 'value'))
  38. * Becomes:
  39. * 'key.key2.key3' => 'value'
  40. *
  41. * This function takes an array by reference and will modify it
  42. *
  43. * @param array &$messages The array that will be flattened
  44. * @param array $subnode Current subnode being parsed, used internally for recursive calls
  45. * @param string $path Current path being parsed, used internally for recursive calls
  46. */
  47. private function flatten(array &$messages, array $subnode = null, $path = null)
  48. {
  49. if (null === $subnode) {
  50. $subnode =& $messages;
  51. }
  52. foreach ($subnode as $key => $value) {
  53. if (is_array($value)) {
  54. $nodePath = $path ? $path.'.'.$key : $key;
  55. $this->flatten($messages, $value, $nodePath);
  56. if (null === $path) {
  57. unset($messages[$key]);
  58. }
  59. } elseif (null !== $path) {
  60. $messages[$path.'.'.$key] = $value;
  61. }
  62. }
  63. }
  64. }