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

UnknownPropertiesItemConverter   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 53
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Test Coverage

Coverage 100%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 8
c 3
b 0
f 0
lcom 1
cbo 0
dl 0
loc 53
ccs 27
cts 27
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 1
A fromClass() 0 10 1
B convert() 0 22 6
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