1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
4
|
|
|
|
5
|
|
|
namespace Stratadox\Hydrator; |
6
|
|
|
|
7
|
|
|
use Closure; |
8
|
|
|
use ReflectionClass; |
9
|
|
|
use Throwable; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Hydrates an object from array input. |
13
|
|
|
* |
14
|
|
|
* @package Stratadox\Hydrate |
15
|
|
|
* @author Stratadox |
16
|
|
|
*/ |
17
|
|
|
final class SimpleHydrator implements Hydrates |
18
|
|
|
{ |
19
|
|
|
private $class; |
20
|
|
|
private $setter; |
21
|
|
|
private $observer; |
22
|
|
|
|
23
|
|
|
private function __construct( |
24
|
|
|
ReflectionClass $reflector, |
25
|
|
|
ObservesHydration $observer, |
26
|
|
|
?Closure $setter |
27
|
|
|
) { |
28
|
|
|
$this->class = $reflector; |
29
|
|
|
$this->observer = $observer; |
30
|
|
|
$this->setter = $setter ?: function (string $attribute, $value) |
31
|
|
|
{ |
32
|
|
|
$this->$attribute = $value; |
33
|
|
|
}; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Creates a new simple hydrator. |
38
|
|
|
* |
39
|
|
|
* @param string $class The class to hydrate. |
40
|
|
|
* @param Closure|null $setter The closure that writes the values. |
41
|
|
|
* @param ObservesHydration|null $observer Object that gets updated with the |
42
|
|
|
* hydrating instance. |
43
|
|
|
* @return self The mapped hydrator. |
44
|
|
|
*/ |
45
|
|
|
public static function forThe( |
46
|
|
|
string $class, |
47
|
|
|
Closure $setter = null, |
48
|
|
|
ObservesHydration $observer = null |
49
|
|
|
) : self |
50
|
|
|
{ |
51
|
|
|
return new self( |
52
|
|
|
new ReflectionClass($class), |
53
|
|
|
$observer ?: BlindObserver::add(), |
54
|
|
|
$setter |
55
|
|
|
); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** @inheritdoc */ |
59
|
|
|
public function fromArray(array $data) |
60
|
|
|
{ |
61
|
|
|
try { |
62
|
|
|
$object = $this->class->newInstanceWithoutConstructor(); |
63
|
|
|
$this->observer->hydrating($object); |
64
|
|
|
foreach ($data as $attribute => $value) { |
65
|
|
|
$this->setter->call($object, $attribute, $value); |
66
|
|
|
} |
67
|
|
|
return $object; |
68
|
|
|
} catch (Throwable $exception) { |
69
|
|
|
throw HydrationFailed::encountered($exception, $this->class); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|