ArrayHydrator   A
last analyzed

Complexity

Total Complexity 10

Size/Duplication

Total Lines 74
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 23
c 0
b 0
f 0
dl 0
loc 74
ccs 23
cts 23
cp 1
rs 10
wmc 10

4 Methods

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