AbstractImporter   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 24
dl 0
loc 68
rs 10
c 0
b 0
f 0
wmc 13

6 Methods

Rating   Name   Duplication   Size   Complexity  
A cleanup() 0 2 1
A __construct() 0 3 1
A getColumnValue() 0 7 2
A validateResource() 0 14 3
A getTranslatableColumnValue() 0 12 2
A getAvailableLocales() 0 15 4
1
<?php
2
3
/*
4
 * This file was created by developers working at BitBag
5
 * Do you need more information about us and what we do? Visit our https://bitbag.io website!
6
 * We are hiring developers from all over the world. Join us and start your new, exciting adventure and become part of us: https://bitbag.io/career
7
*/
8
9
declare(strict_types=1);
10
11
namespace BitBag\SyliusCmsPlugin\Importer;
12
13
use Sylius\Component\Resource\Model\ResourceInterface;
14
use Symfony\Component\Validator\Validator\ValidatorInterface;
15
16
abstract class AbstractImporter implements ImporterInterface
17
{
18
    /** @var ValidatorInterface */
19
    private $validator;
20
21
    public function __construct(ValidatorInterface $validator)
22
    {
23
        $this->validator = $validator;
24
    }
25
26
    public function cleanup(): void
27
    {
28
    }
29
30
    protected function getColumnValue(string $column, array $row)
31
    {
32
        if (array_key_exists($column, $row)) {
33
            return $row[$column];
34
        }
35
36
        return null;
37
    }
38
39
    protected function getTranslatableColumnValue(
40
        string $column,
41
        $locale,
42
        array $row
43
    ) {
44
        $column = str_replace('__locale__', '_' . $locale, $column);
45
46
        if (array_key_exists($column, $row)) {
47
            return $row[$column];
48
        }
49
50
        return null;
51
    }
52
53
    protected function getAvailableLocales(array $translatableColumns, array $columns): array
54
    {
55
        $locales = [];
56
57
        foreach ($translatableColumns as $translatableColumn) {
58
            $translatableColumn = str_replace('__locale__', '_', $translatableColumn);
59
60
            foreach ($columns as $column) {
61
                if (0 === strpos($column, $translatableColumn)) {
62
                    $locales[] = str_replace($translatableColumn, '', $column);
63
                }
64
            }
65
        }
66
67
        return array_unique($locales);
68
    }
69
70
    protected function validateResource(ResourceInterface $resource, array $groups): void
71
    {
72
        $errors = $this->validator->validate($resource, null, $groups);
73
74
        if (0 < count($errors)) {
75
            $message = '';
76
77
            foreach ($errors as $error) {
78
                $message .= lcfirst(rtrim($error->getMessage(), '.')) . ', ';
79
            }
80
81
            $message = ucfirst(rtrim($message, ', ')) . '.';
82
83
            throw new \RuntimeException($message);
84
        }
85
    }
86
}
87