Passed
Push — heiglandreas-patch-1 ( 8b9b12...3c2950 )
by Andreas
05:14 queued 03:50
created

ArrayHydrator::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

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