Completed
Push — master ( 9ab091...ed74e2 )
by Alexpts
03:14
created

ModelClosure::getFillFn()   C

Complexity

Conditions 7
Paths 2

Size

Total Lines 26
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 16
CRAP Score 7

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 26
ccs 16
cts 16
cp 1
rs 6.7273
cc 7
eloc 14
nc 2
nop 0
crap 7
1
<?php
2
namespace PTS\DataTransformer;
3
4
class ModelClosure
5
{
6
    /** @var \Closure */
7
    protected $fillFn;
8
    /** @var \Closure */
9
    protected $toDataFn;
10
11
    /**
12
     * @return \Closure
13
     */
14 4
    public function getToDataFn()
15
    {
16 4
        if (!$this->toDataFn) {
17
            $this->toDataFn = function (array $mapping, TypeConverter $typeConverter) {
18 2
                $props = [];
19
20 2
                foreach ($mapping as $name => $prop) {
21 2
                    $getter = isset($prop['get']) ? $prop['get'] : null;
22 2
                    $propVal = isset($prop['prop']) ? $prop['prop'] : null;
23
24 2
                    if ($getter) {
25 2
                        $method = is_array($getter) ? $getter[0] : $getter;
26 2
                        $args = is_array($getter) ? $getter[1] : [];
27 2
                        $val = call_user_func_array([$this, $method], $args);
28 2
                    } elseif ($propVal) {
29 2
                        $val = $this->{$propVal};
30 2
                    } else {
31 1
                        throw new \InvalidArgumentException('Bad mapping config');
32
                    }
33
34 2
                    if ($val !== null) {
35 2
                        $props[$name] = $typeConverter->toStorage($val, $prop);
36 2
                    }
37 2
                }
38
39 1
                return $props;
40
            };
41 4
        }
42
43 4
        return $this->toDataFn;
44
    }
45
46
    /**
47
     * @return \Closure
48
     */
49 3
    public function getFillFn()
50
    {
51 3
        if (!$this->fillFn) {
52 1
            $this->fillFn = function (array $doc, array $mapping, TypeConverter $typeConverter) {
53
54 1
                foreach ($doc as $name => $val) {
55 1
                    if (!array_key_exists($name, $mapping)) {
56 1
                        continue;
57
                    }
58
59 1
                    $prop = $mapping[$name];
60
61 1
                    $modelName = array_key_exists('prop', $prop) ? $prop['prop'] : $name;
62 1
                    $setter = array_key_exists('set', $prop) ? $prop['set'] : null;
63
64 1
                    $val = $typeConverter->toModel($val, $prop);
65
66
                    $setter
67 1
                        ? call_user_func([$this, $setter], $val)
68 1
                        : $this->{$modelName} = $val;
69 1
                }
70 1
            };
71 3
        }
72
73 3
        return $this->fillFn;
74
    }
75
}