Skip to content

Commit 202da81

Browse files
authored
Merge pull request #12 from TheFehr/master
Implement recursive splitting for translation keys
2 parents c95c597 + e8107c2 commit 202da81

File tree

1 file changed

+12
-30
lines changed

1 file changed

+12
-30
lines changed

src/Controllers/Ops.php

+12-30
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace ctf0\Lingo\Controllers;
44

5+
use Illuminate\Support\Collection;
56
use ZipStream\ZipStream;
67
use Illuminate\Support\Arr;
78
use Illuminate\Support\Str;
@@ -101,40 +102,21 @@ protected function saveToFile($file, $data, $package_name = null)
101102
return true;
102103
}
103104

104-
protected function recSave($pre_format, $key, $code, $v)
105+
private static function explodeTranlsationKey(string $nestedTranslationKey, string|null $value): array
105106
{
106-
if (strpos($key, '.')) {
107-
$assoc = [];
108-
$exp = explode('.', $key);
107+
$doneSplitting = !Str::contains($nestedTranslationKey, '.');
109108

110-
// convert array dot to associative
111-
while (!empty($exp)) {
112-
$assoc = [array_pop($exp) => $assoc];
113-
}
114-
115-
// set value to last key
116-
Arr::set($assoc, $key, $v);
117-
118-
// get root key
119-
$first_key = strtok($key, '.');
120-
121-
// hacky fix to avoid indexed nesting
122-
$final = array_pop($assoc);
123-
$a = key($final);
124-
$b = current($final);
109+
if ($doneSplitting) return [$nestedTranslationKey => $value];
125110

126-
// 3rd level deep
127-
if (is_array($b)) {
128-
$c = key($b);
129-
$d = current($b);
111+
$currentLevel = collect(explode('#', Str::replaceFirst('.', '#', $nestedTranslationKey)));
112+
$collection = collect([$currentLevel[0] => self::explodeTranlsationKey($currentLevel[1], $value)]);
113+
return $collection->toArray();
114+
}
130115

131-
$pre_format[$code][$first_key][$a][$c] = $d;
132-
} else {
133-
$pre_format[$code][$first_key][$a] = $b;
134-
}
135-
} else {
136-
$pre_format[$code][$key] = $v;
137-
}
116+
protected function recSave(array $pre_format, string $key, string $code, string|null $v)
117+
{
118+
$codeContent = collect($pre_format)->get($code, []);
119+
$pre_format[$code] = collect($codeContent)->mergeRecursive(self::explodeTranlsationKey($key, $v))->toArray();
138120

139121
return $pre_format;
140122
}

0 commit comments

Comments
 (0)