Completed
Push — master ( 0473d3...bc9ba5 )
by Markus
24:46
created

UnknownPropertiesItemConverter::fromClass()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 10
ccs 7
cts 7
cp 1
rs 9.4285
cc 1
eloc 7
nc 1
nop 3
crap 1
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 = $knownProperties;
18 3
        $this->targetProperty = $targetProperty;
19 3
        $this->skipEmptyKey = $skipEmptyKey;
20
21 3
        $this->knownProperties[] = $this->targetProperty;
22 3
    }
23
24 1
    public static function fromClass($cls, $targetProperty='ATTRIBUTES', $skipEmptyKey=true)
25
    {
26 1
        $r = new \ReflectionClass($cls);
27 1
        $properties = $r->getProperties();
28 1
        $properties = array_map(function (\ReflectionProperty $e) {
29 1
            return $e->getName();
30 1
        }, $properties);
31
32 1
        return new self($properties, $targetProperty, $skipEmptyKey);
33
    }
34
35 3
    public function convert($input)
36
    {
37 3
        $unknownProperties = array_udiff(array_keys($input), $this->knownProperties, 'strcasecmp');
38
39
        //has unknown properties
40 3
        if (count($unknownProperties) > 0) {
41
            //target property does not exist => make it an array
42 3
            if (!isset($input[$this->targetProperty])) {
43 3
                $input[$this->targetProperty] = [];
44 3
            }
45
46
            //copy unknown properties to target property and remove them from input
47 3
            foreach ($unknownProperties as $property) {
48 3
                if (!$this->skipEmptyKey || !empty($property)) {
49 3
                    $input[$this->targetProperty][$property] = $input[$property];
50 3
                }
51 3
                unset($input[$property]);
52 3
            }
53 3
        }
54
55 3
        return $input;
56
    }
57
58
}
59