|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Nikaia\TranslationSheet\Translation; |
|
4
|
|
|
|
|
5
|
|
|
use Illuminate\Support\Collection; |
|
6
|
|
|
use Illuminate\Support\Str; |
|
7
|
|
|
|
|
8
|
|
|
class Transformer |
|
9
|
|
|
{ |
|
10
|
|
|
private $locales = []; |
|
11
|
3 |
|
|
|
12
|
|
|
public function setLocales($locales) |
|
13
|
3 |
|
{ |
|
14
|
|
|
$this->locales = $locales; |
|
15
|
3 |
|
|
|
16
|
|
|
return $this; |
|
17
|
|
|
} |
|
18
|
3 |
|
|
|
19
|
|
|
public function transform(Collection $translations) |
|
20
|
|
|
{ |
|
21
|
3 |
|
return $translations |
|
22
|
3 |
|
->sortBy('locale') |
|
23
|
|
|
->groupBy('full_key') |
|
24
|
3 |
|
->map(function (Collection $translation) { |
|
25
|
|
|
$firstLocale = $translation->first(); |
|
26
|
3 |
|
|
|
27
|
3 |
|
$row = []; |
|
28
|
|
|
$row['full_key'] = $firstLocale->full_key; |
|
29
|
|
|
|
|
30
|
3 |
|
$translation = $translation |
|
31
|
|
|
->groupBy('locale') |
|
32
|
3 |
|
->map(function (Collection $item) { |
|
33
|
3 |
|
return $item->first(); |
|
34
|
|
|
}); |
|
35
|
3 |
|
|
|
36
|
|
|
$translation = $this->ensureWeHaveAllLocales($translation); |
|
37
|
3 |
|
|
|
38
|
3 |
|
$localesValues = []; |
|
39
|
3 |
|
foreach ($this->locales as $locale) { |
|
40
|
3 |
|
$item = $translation->get($locale); |
|
41
|
3 |
|
$value = ! is_null($item) && isset($item->value) ? $item->value : ''; |
|
42
|
|
|
$localesValues [$locale] = $value; |
|
43
|
|
|
} |
|
44
|
3 |
|
|
|
45
|
|
|
$row = array_merge($row, $localesValues); |
|
46
|
3 |
|
|
|
47
|
3 |
|
$row = array_merge($row, [ |
|
48
|
3 |
|
'namespace' => ! is_null($firstLocale->namespace) ? $firstLocale->namespace : '', |
|
49
|
3 |
|
'group' => ! is_null($firstLocale->group) ? $firstLocale->group : '', |
|
50
|
3 |
|
'key' => $firstLocale->key, |
|
51
|
|
|
'source_file' => $this->formatSourceFile($firstLocale), |
|
52
|
|
|
]); |
|
53
|
3 |
|
|
|
54
|
3 |
|
return array_values($row); |
|
55
|
|
|
}) |
|
56
|
3 |
|
->sortBy(function ($product, $key) { |
|
57
|
3 |
|
return $key; |
|
58
|
3 |
|
}) |
|
59
|
|
|
->values(); |
|
60
|
|
|
} |
|
61
|
3 |
|
|
|
62
|
|
|
private function ensureWeHaveAllLocales(Collection $translation) |
|
63
|
3 |
|
{ |
|
64
|
3 |
|
foreach ($this->locales as $locale) { |
|
65
|
1 |
|
if (! $translation->get($locale)) { |
|
66
|
|
|
$translation->put($locale, new Item); |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
3 |
|
|
|
70
|
|
|
return $translation; |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
private function formatSourceFile($firstLocale) |
|
74
|
|
|
{ |
|
75
|
|
|
if (Str::endsWith($firstLocale->source_file, ['.json'])) { |
|
76
|
|
|
return '{locale}.json'; |
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
|
|
return str_replace($firstLocale->locale . '/', '{locale}/', $firstLocale->source_file); |
|
80
|
|
|
} |
|
81
|
|
|
} |
|
82
|
|
|
|