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
|
|
|
|