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