UnknownPropertiesItemConverter   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 0
dl 0
loc 57
ccs 26
cts 26
cp 1
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 10 2
A fromClass() 0 10 1
B convert() 0 26 7
1
<?php
2
3
namespace Mathielen\DataImport\ItemConverter;
4
5
use Ddeboer\DataImport\ItemConverter\ItemConverterInterface;
6
7
class UnknownPropertiesItemConverter implements ItemConverterInterface
8
{
9
    private $knownProperties;
10
11
    private $targetProperty;
12
13
    private $skipEmptyKey;
14
15 3
    public function __construct(array $knownProperties, $targetProperty = 'ATTRIBUTES', $skipEmptyKey = true)
16
    {
17 3
        $this->knownProperties = array_map('strtoupper', $knownProperties);
18 3
        $this->targetProperty = $targetProperty;
19 3
        $this->skipEmptyKey = $skipEmptyKey;
20
21 3
        if (!in_array(strtoupper($this->targetProperty), $this->knownProperties)) {
22 3
            $this->knownProperties[] = strtoupper($this->targetProperty);
23
        }
24 3
    }
25
26 1
    public static function fromClass($cls, $targetProperty = 'ATTRIBUTES', $skipEmptyKey = true)
27
    {
28 1
        $r = new \ReflectionClass($cls);
29 1
        $properties = $r->getProperties();
30
        $properties = array_map(function (\ReflectionProperty $e) {
31 1
            return $e->getName();
32 1
        }, $properties);
33
34 1
        return new self($properties, $targetProperty, $skipEmptyKey);
35
    }
36
37 3
    public function convert($input)
38
    {
39 3
        $currentKeys = array_keys($input);
40 3
        $unknownProperties = array_udiff($currentKeys, $this->knownProperties, function ($a, $b) {
41 3
            return strcasecmp(str_replace('_', '', $a), str_replace('_', '', $b)); //compare the keys, without _
42 3
        });
43
44
        //has unknown properties
45 3
        if (count($unknownProperties) > 0) {
46
            //target property does not exist => make it an array
47 3
            if (!isset($input[$this->targetProperty])) {
48 3
                $input[$this->targetProperty] = [];
49
            }
50
51
            //copy unknown properties to target property and remove them from input
52 3
            foreach ($unknownProperties as $property) {
53
                //if key is not empty and value of key is not empty => copy it to target property-array
54 3
                if (!$this->skipEmptyKey || !empty($property) && !empty($input[$property])) {
55 3
                    $input[$this->targetProperty][$property] = $input[$property];
56
                }
57 3
                unset($input[$property]);
58
            }
59
        }
60
61 3
        return $input;
62
    }
63
}
64