Passed
Push — heiglandreas-patch-1 ( 8f4377 )
by Andreas
03:21
created

ArrayHydrator::hydrationValue()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 3
dl 0
loc 6
ccs 0
cts 4
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * SocialConnect project
4
 * @author: Patsura Dmitry @ovr <[email protected]>
5
 */
6
7
namespace SocialConnect\Common;
8
9
final class ArrayHydrator
10
{
11
    /**
12
     * Hydration map
13
     *
14
     * @var array
15
     */
16
    protected $map;
17
18
    /**
19
     * @param array $map
20
     */
21
    public function __construct(array $map)
22
    {
23
        $this->map = $map;
24
    }
25
26
    /**
27
     * @param array $path
28
     * @param string|callable $keyToOrFn
29
     * @param array $input
30
     * @param object $targetObject
31
     * @return void
32
     */
33
    protected function referenceRecursiveHydration(array $path, $keyToOrFn, array $input, $targetObject): void
34
    {
35
        $keyFrom = array_shift($path);
36
37
        if (isset($input[$keyFrom])) {
38
            if (count($path) === 0) {
39
                self::hydrationValue($keyToOrFn, $input[$keyFrom], $targetObject);
40
            } else {
41
                $this->referenceRecursiveHydration($path, $keyToOrFn, $input[$keyFrom], $targetObject);
42
            }
43
        }
44
    }
45
46
    /**
47
     * @param string|callable $keyToOrFn
48
     * @param mixed $value
49
     * @param object $targetObject
50
     */
51
    protected static function hydrationValue($keyToOrFn, $value, $targetObject): void
52
    {
53
        if (is_callable($keyToOrFn)) {
54
            $keyToOrFn($value, $targetObject);
55
        } else {
56
            $targetObject->{$keyToOrFn} = $value;
57
        }
58
    }
59
60
    /**
61
     * Hydrate $targetObject
62
     *
63
     * @param object $targetObject
64
     * @param array $input
65
     * @return object
66
     */
67
    public function hydrate($targetObject, array $input)
68
    {
69
        foreach ($this->map as $keyFrom => $keyToOrFn) {
70
            if (strpos($keyFrom, '.')) {
71
                $this->referenceRecursiveHydration(
72
                    explode('.', $keyFrom),
73
                    $keyToOrFn,
74
                    $input,
75
                    $targetObject
76
                );
77
            } else if (isset($input[$keyFrom])) {
78
                self::hydrationValue($keyToOrFn, $input[$keyFrom], $targetObject);
79
            }
80
        }
81
82
        return $targetObject;
83
    }
84
}
85