[Translation] refactor ArrayLoader::flatten

This commit is contained in:
Saif Eddin G 2019-05-28 19:14:45 +01:00 committed by Fabien Potencier
parent 7f40716618
commit 5b0544691e

View File

@ -25,7 +25,7 @@ class ArrayLoader implements LoaderInterface
*/ */
public function load($resource, $locale, $domain = 'messages') public function load($resource, $locale, $domain = 'messages')
{ {
$this->flatten($resource); $resource = $this->flatten($resource);
$catalogue = new MessageCatalogue($locale); $catalogue = new MessageCatalogue($locale);
$catalogue->add($resource, $domain); $catalogue->add($resource, $domain);
@ -39,28 +39,20 @@ class ArrayLoader implements LoaderInterface
* 'key' => ['key2' => ['key3' => 'value']] * 'key' => ['key2' => ['key3' => 'value']]
* Becomes: * Becomes:
* 'key.key2.key3' => 'value' * 'key.key2.key3' => 'value'
*
* This function takes an array by reference and will modify it
*
* @param array &$messages The array that will be flattened
* @param array $subnode Current subnode being parsed, used internally for recursive calls
* @param string $path Current path being parsed, used internally for recursive calls
*/ */
private function flatten(array &$messages, array $subnode = null, $path = null) private function flatten(array $messages): array
{ {
if (null === $subnode) { $result = [];
$subnode = &$messages; foreach ($messages as $key => $value) {
}
foreach ($subnode as $key => $value) {
if (\is_array($value)) { if (\is_array($value)) {
$nodePath = $path ? $path.'.'.$key : $key; foreach ($this->flatten($value) as $k => $v) {
$this->flatten($messages, $value, $nodePath); $result[$key.'.'.$k] = $v;
if (null === $path) {
unset($messages[$key]);
} }
} elseif (null !== $path) { } else {
$messages[$path.'.'.$key] = $value; $result[$key] = $value;
} }
} }
return $result;
} }
} }