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

ModelClosure::createFillFn()   B

Complexity

Conditions 6
Paths 1

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 21
ccs 11
cts 11
cp 1
rs 8.7624
cc 6
eloc 12
nc 1
nop 0
crap 6
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
}