Passed
Push — master ( 541ffa...79bd89 )
by Christian
09:50
created

ImporterFromExcel   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 28
c 1
b 0
f 0
dl 0
loc 60
ccs 30
cts 30
cp 1
rs 10
wmc 11

4 Methods

Rating   Name   Duplication   Size   Complexity  
A import() 0 6 1
A parseTranslations() 0 19 5
A importSheets() 0 11 2
A getSheets() 0 16 3
1
<?php
2
3
namespace Omatech\Mage\Core\Adapters\Translations\Importers;
4
5
use Box\Spout\Common\Type;
6
use Box\Spout\Reader\ReaderFactory;
7
use Omatech\Mage\Core\Domains\Translations\Contracts\ImportTranslationInterface;
8
use Rap2hpoutre\FastExcel\FastExcel;
9
10
class ImporterFromExcel implements ImportTranslationInterface
11
{
12 3
    public function import(string $path, string $locale = ''): array
13
    {
14 3
        $sheetNames = $this->getSheets($path, $locale);
15 3
        $sheets = $this->importSheets($path, $sheetNames);
16
17 3
        return $this->parseTranslations($sheetNames, $sheets);
18
    }
19
20 3
    private function getSheets(string $path, string $locale = ''): array
21
    {
22 3
        $sheetNames = [];
23
24 3
        $reader = ReaderFactory::create(Type::XLSX);
25 3
        $reader->open($path);
26
27 3
        foreach ($reader->getSheetIterator() as $sheet) {
28 3
            array_push($sheetNames, $sheet->getName());
29
        }
30
31 3
        if ('' != $locale) {
32 2
            $sheetNames = [0 => $locale];
33
        }
34
35 3
        return $sheetNames;
36
    }
37
38 3
    private function importSheets(string $path, array $sheetNames): array
39
    {
40 3
        $sheets = (new FastExcel());
41
42 3
        if (count($sheetNames) > 1) {
43 1
            $sheets = $sheets->importSheets($path)->toArray();
44
        } else {
45 2
            $sheets = [$sheets->sheet(key($sheetNames) + 1)->import($path)->toArray()];
46
        }
47
48 3
        return $sheets;
49
    }
50
51 3
    private function parseTranslations(array $sheetNames, array $sheets): array
52
    {
53 3
        $translations = [];
54 3
        $parsedKeys = [];
55
56 3
        foreach ($sheets as $lang => $trans) {
57 3
            $translations[$sheetNames[$lang]] = $trans;
58
        }
59
60 3
        foreach ($translations as $lang => $keys) {
61 3
            foreach ($keys as $key) {
62 3
                if ('' != $key['key2']) {
63 3
                    $parsedKeys[$key['key2']]['key'] = $key['key2'];
64 3
                    $parsedKeys[$key['key2']]['value'][$lang] = $key['value'];
65
                }
66
            }
67
        }
68
69 3
        return array_values($parsedKeys);
70
    }
71
}
72