Skip to content

Commit

Permalink
[Translation] Prevent creating empty keys when key ends with a period
Browse files Browse the repository at this point in the history
[Translation] create getKeyParts() to keep periods at start or end of the key

[Translation] Simplify test cases by removing blank spaces
  • Loading branch information
javleds committed Oct 13, 2023
1 parent de237e5 commit 4e40057
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 1 deletion.
28 changes: 28 additions & 0 deletions Tests/Util/ArrayConverterTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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',
],
],
],
];
}
}
44 changes: 43 additions & 1 deletion Util/ArrayConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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];
}
Expand Down Expand Up @@ -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;
}
}

0 comments on commit 4e40057

Please sign in to comment.