|
1 <?php |
|
2 |
|
3 /* |
|
4 * This file is part of the Symfony package. |
|
5 * |
|
6 * (c) Fabien Potencier <fabien@symfony.com> |
|
7 * |
|
8 * For the full copyright and license information, please view the LICENSE |
|
9 * file that was distributed with this source code. |
|
10 */ |
|
11 |
|
12 namespace Symfony\Component\Translation\Loader; |
|
13 |
|
14 use Symfony\Component\Translation\MessageCatalogue; |
|
15 |
|
16 /** |
|
17 * ArrayLoader loads translations from a PHP array. |
|
18 * |
|
19 * @author Fabien Potencier <fabien@symfony.com> |
|
20 * |
|
21 * @api |
|
22 */ |
|
23 class ArrayLoader implements LoaderInterface |
|
24 { |
|
25 /** |
|
26 * {@inheritdoc} |
|
27 * |
|
28 * @api |
|
29 */ |
|
30 public function load($resource, $locale, $domain = 'messages') |
|
31 { |
|
32 $this->flatten($resource); |
|
33 $catalogue = new MessageCatalogue($locale); |
|
34 $catalogue->add($resource, $domain); |
|
35 |
|
36 return $catalogue; |
|
37 } |
|
38 |
|
39 /** |
|
40 * Flattens an nested array of translations |
|
41 * |
|
42 * The scheme used is: |
|
43 * 'key' => array('key2' => array('key3' => 'value')) |
|
44 * Becomes: |
|
45 * 'key.key2.key3' => 'value' |
|
46 * |
|
47 * This function takes an array by reference and will modify it |
|
48 * |
|
49 * @param array $messages the array that will be flattened |
|
50 * @param array $subnode current subnode being parsed, used internally for recursive calls |
|
51 * @param string $path current path being parsed, used internally for recursive calls |
|
52 */ |
|
53 private function flatten(array &$messages, array $subnode = null, $path = null) |
|
54 { |
|
55 if (null === $subnode) { |
|
56 $subnode =& $messages; |
|
57 } |
|
58 foreach ($subnode as $key => $value) { |
|
59 if (is_array($value)) { |
|
60 $nodePath = $path ? $path.'.'.$key : $key; |
|
61 $this->flatten($messages, $value, $nodePath); |
|
62 if (null === $path) { |
|
63 unset($messages[$key]); |
|
64 } |
|
65 } elseif (null !== $path) { |
|
66 $messages[$path.'.'.$key] = $value; |
|
67 } |
|
68 } |
|
69 } |
|
70 } |