Completed
Push — master ( 58a98c...5e25b8 )
by Alexpts
02:51
created

ModelClosure::getFillFn()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

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