More tidying.
[yaffs-website] / vendor / symfony / translation / Loader / ArrayLoader.php
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 class ArrayLoader implements LoaderInterface
22 {
23     /**
24      * {@inheritdoc}
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
32         return $catalogue;
33     }
34
35     /**
36      * Flattens an nested array of translations.
37      *
38      * The scheme used is:
39      *   'key' => array('key2' => array('key3' => 'value'))
40      * Becomes:
41      *   'key.key2.key3' => 'value'
42      *
43      * This function takes an array by reference and will modify it
44      *
45      * @param array  &$messages The array that will be flattened
46      * @param array  $subnode   Current subnode being parsed, used internally for recursive calls
47      * @param string $path      Current path being parsed, used internally for recursive calls
48      */
49     private function flatten(array &$messages, array $subnode = null, $path = null)
50     {
51         if (null === $subnode) {
52             $subnode = &$messages;
53         }
54         foreach ($subnode as $key => $value) {
55             if (is_array($value)) {
56                 $nodePath = $path ? $path.'.'.$key : $key;
57                 $this->flatten($messages, $value, $nodePath);
58                 if (null === $path) {
59                     unset($messages[$key]);
60                 }
61             } elseif (null !== $path) {
62                 $messages[$path.'.'.$key] = $value;
63             }
64         }
65     }
66 }