forked from contentful/contentful-core.php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathObjectHydrator.php
68 lines (59 loc) · 1.64 KB
/
ObjectHydrator.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
<?php
/**
* This file is part of the contentful/contentful-core package.
*
* @copyright 2015-2018 Contentful GmbH
* @license MIT
*/
declare(strict_types=1);
namespace Atolye15\Core\ResourceBuilder;
/**
* Class ObjectHydrator.
*
* Utility class for handling updating private or protected properties of an object.
*/
class ObjectHydrator
{
/**
* @var \Closure[]
*/
private $hydrators = [];
/**
* If given a class name as target, the hydrator will create an instance of that class,
* but skipping the constructor. The hydrator will then update the internal properties,
* according to the keys defined in the $data parameter.
*
* @param string|object $target
* @param array $data
*
* @return object
*/
public function hydrate($target, array $data)
{
$class = \is_object($target) ? \get_class($target) : $target;
if (\is_string($target)) {
$target = (new \ReflectionClass($class))
->newInstanceWithoutConstructor()
;
}
$hydrator = $this->getHydrator($class);
$hydrator($target, $data);
return $target;
}
/**
* @param string $class
*
* @return \Closure
*/
private function getHydrator($class): \Closure
{
if (isset($this->hydrators[$class])) {
return $this->hydrators[$class];
}
return $this->hydrators[$class] = \Closure::bind(function ($object, array $properties) {
foreach ($properties as $property => $value) {
$object->$property = $value;
}
}, \null, $class);
}
}