Completed
Push — master ( 9cad2d...e5625e )
by Markus
07:28
created

UnknownPropertiesItemConverter::convert()   C

Complexity

Conditions 7
Paths 3

Size

Total Lines 26
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 7

Importance

Changes 4
Bugs 1 Features 0
Metric Value
c 4
b 1
f 0
dl 0
loc 26
ccs 13
cts 13
cp 1
rs 6.7272
cc 7
eloc 12
nc 3
nop 1
crap 7
1
<?php
2
namespace Mathielen\DataImport\ItemConverter;
3
4
use Ddeboer\DataImport\ItemConverter\ItemConverterInterface;
5
6
class UnknownPropertiesItemConverter implements ItemConverterInterface
7
{
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
}
65