4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Translation\Util
;
15 * ArrayConverter generates tree like structure from a message catalogue.
17 * 'foo.bar1' => 'test1',
18 * 'foo.bar2' => 'test2'
19 * converts to follows:
24 * @author Gennady Telegin <gtelegin@gmail.com>
29 * Converts linear messages array to tree-like array.
30 * For example this rray('foo.bar' => 'value') will be converted to array('foo' => array('bar' => 'value')).
32 * @param array $messages Linear messages array
34 * @return array Tree-like messages array
36 public static function expandToTree(array $messages)
40 foreach ($messages as $id => $value) {
41 $referenceToElement = &self
::getElementByPath($tree, explode('.', $id));
43 $referenceToElement = $value;
45 unset($referenceToElement);
51 private static function &getElementByPath(array &$tree, array $parts)
56 foreach ($parts as $i => $part) {
57 if (isset($elem[$part]) && is_string($elem[$part])) {
62 * $tree['foo'] was string before we found array {bar: test2}.
63 * Treat new element as string too, e.g. add $tree['foo.bar'] = 'test2';
65 $elem = &$elem[implode('.', array_slice($parts, $i))];
68 $parentOfElem = &$elem;
69 $elem = &$elem[$part];
72 if (is_array($elem) && count($elem) > 0 && $parentOfElem) {
77 * $tree['foo'] was array = {bar: 'test1'} before we found string constant `foo`.
78 * Cancel treating $tree['foo'] as array and cancel back it expansion,
79 * e.g. make it $tree['foo.bar'] = 'test1' again.
81 self
::cancelExpand($parentOfElem, $part, $elem);
87 private static function cancelExpand(array &$tree, $prefix, array $node)
91 foreach ($node as $id => $value) {
92 if (is_string($value)) {
93 $tree[$prefix.$id] = $value;
95 self
::cancelExpand($tree, $prefix.$id, $value);