Completed
Push — master ( a624e1...736705 )
by Nassif
12:28
created

Transformer   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 65
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 2
dl 0
loc 65
ccs 34
cts 34
cp 1
rs 10
c 0
b 0
f 0

3 Methods

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