Completed
Pull Request — master (#44)
by
unknown
08:30
created

AttributeOption::convert()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 10
c 1
b 0
f 0
dl 0
loc 16
rs 9.9332
cc 3
nc 3
nop 2
1
<?php
2
3
namespace Flagbit\Bundle\TableAttributeBundle\ArrayConverter\FlatToStandard;
4
5
use Akeneo\Tool\Component\Connector\ArrayConverter\ArrayConverterInterface;
6
7
class AttributeOption implements ArrayConverterInterface
8
{
9
    /**
10
     * @var ArrayConverterInterface
11
     */
12
    protected $baseArrayConverter;
13
14
    public function __construct(ArrayConverterInterface $baseArrayConverter)
15
    {
16
        $this->baseArrayConverter = $baseArrayConverter;
17
    }
18
19
    public function convert(array $item, array $options = [])
20
    {
21
        $convertedItems = [];
22
        $baseItem = [];
23
24
        foreach ($item as $field => $data) {
25
            if (preg_match('/^(constraints|type|type_config\-\w+)$/', $field)) {
26
                $convertedItems = $this->convertItem($field, $data, $convertedItems);
27
            } else {
28
                $baseItem[$field] = $data;
29
            }
30
        }
31
32
        return array_merge(
33
            $this->baseArrayConverter->convert($baseItem, $options),
34
            $convertedItems
35
        );
36
    }
37
38
    protected function convertItem($field, $data, array $convertedItem)
39
    {
40
        if (!array_key_exists('type_config', $convertedItem)) {
41
            $convertedItem['type_config'] = [];
42
        }
43
44
        switch ($field) {
45
            case 'constraints':
46
                $constraints = explode(',', $data);
47
                $convertedItem['constraints'] = array_fill_keys($constraints, []);
48
                break;
49
50
            case 'type_config-is_decimal':
51
                if (!empty($data)) {
52
                    $convertedItem['type_config']['is_decimal'] = (bool) $data;
53
                }
54
                break;
55
56
            case 'type_config-options_url':
57
                if (!empty($data)) {
58
                    $convertedItem['type_config']['options_url'] = $data;
59
                }
60
                break;
61
62
            case 'type_config-options':
63
                if (!empty($data)) {
64
                    $convertedItem['type_config']['options'] = json_decode($data, true);
65
                }
66
                break;
67
68
            default:
69
                $convertedItem[$field] = $data;
70
                break;
71
        }
72
73
        return $convertedItem;
74
    }
75
}
76