diff --git a/Tests/Util/ArrayConverterTest.php b/Tests/Util/ArrayConverterTest.php index 8936ef1a..446130cc 100644 --- a/Tests/Util/ArrayConverterTest.php +++ b/Tests/Util/ArrayConverterTest.php @@ -69,6 +69,34 @@ public static function messagesData() ], ], ], + [ + // input + [ + 'foo.' => 'foo.', + '.bar' => '.bar', + 'abc.abc' => 'value', + 'bcd.bcd.' => 'value', + '.cde.cde.' => 'value', + '.def.def' => 'value', + ], + // expected output + [ + 'foo.' => 'foo.', + '.bar' => '.bar', + 'abc' => [ + 'abc' => 'value', + ], + 'bcd' => [ + 'bcd.' => 'value', + ], + '.cde' => [ + 'cde.' => 'value', + ], + '.def' => [ + 'def' => 'value', + ], + ], + ], ]; } } diff --git a/Util/ArrayConverter.php b/Util/ArrayConverter.php index f69c2e3c..e132e3de 100644 --- a/Util/ArrayConverter.php +++ b/Util/ArrayConverter.php @@ -38,7 +38,7 @@ public static function expandToTree(array $messages) $tree = []; foreach ($messages as $id => $value) { - $referenceToElement = &self::getElementByPath($tree, explode('.', $id)); + $referenceToElement = &self::getElementByPath($tree, self::getKeyParts($id)); $referenceToElement = $value; @@ -65,6 +65,7 @@ private static function &getElementByPath(array &$tree, array $parts) $elem = &$elem[implode('.', \array_slice($parts, $i))]; break; } + $parentOfElem = &$elem; $elem = &$elem[$part]; } @@ -96,4 +97,45 @@ private static function cancelExpand(array &$tree, string $prefix, array $node) } } } + + private static function getKeyParts(string $key) + { + $parts = explode('.', $key); + $partsCount = \count($parts); + + $result = []; + $buffer = ''; + + foreach ($parts as $index => $part) { + if (0 === $index && '' === $part) { + $buffer = '.'; + + continue; + } + + if ($index === $partsCount - 1 && '' === $part) { + $buffer .= '.'; + $result[] = $buffer; + + continue; + } + + if (isset($parts[$index + 1]) && '' === $parts[$index + 1]) { + $buffer .= $part; + + continue; + } + + if ($buffer) { + $result[] = $buffer.$part; + $buffer = ''; + + continue; + } + + $result[] = $part; + } + + return $result; + } }