|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* File was created 07.10.2015 06:35 |
|
4
|
|
|
*/ |
|
5
|
|
|
|
|
6
|
|
|
namespace PeekAndPoke\Component\Slumber\Core\Codec; |
|
7
|
|
|
|
|
8
|
|
|
use PeekAndPoke\Component\Slumber\Core\LookUp\EntityConfig; |
|
9
|
|
|
use PeekAndPoke\Component\Slumber\Core\LookUp\EntityConfigReader; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* @author Karsten J. Gerber <[email protected]> |
|
13
|
|
|
*/ |
|
14
|
|
|
class GenericAwaker implements Awaker |
|
15
|
|
|
{ |
|
16
|
|
|
/** @var EntityConfigReader */ |
|
17
|
|
|
protected $entityConfigLookUp; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* @param EntityConfigReader $entityConfigLookUp |
|
21
|
|
|
*/ |
|
22
|
374 |
|
public function __construct(EntityConfigReader $entityConfigLookUp) |
|
23
|
|
|
{ |
|
24
|
374 |
|
$this->entityConfigLookUp = $entityConfigLookUp; |
|
25
|
374 |
|
} |
|
26
|
|
|
|
|
27
|
|
|
/** |
|
28
|
|
|
* @param mixed $data |
|
29
|
|
|
* @param \ReflectionClass $cls |
|
30
|
|
|
* |
|
31
|
|
|
* @return mixed|null |
|
32
|
|
|
*/ |
|
33
|
14 |
|
public function awake($data, \ReflectionClass $cls) |
|
34
|
|
|
{ |
|
35
|
|
|
// read the config for the given class |
|
36
|
14 |
|
$config = $this->entityConfigLookUp->getEntityConfig($cls); |
|
37
|
|
|
|
|
38
|
14 |
|
if ($config === null) { |
|
39
|
1 |
|
return null; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
// create an instance |
|
43
|
13 |
|
$subject = $config->getCreator()->create($data); |
|
44
|
|
|
|
|
45
|
|
|
// if we do not get an instance we return nothing |
|
46
|
13 |
|
if ($subject === null) { |
|
47
|
1 |
|
return null; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
// NOTICE: creating the instance can change the type (e.g. for polymorphic mapping) |
|
51
|
|
|
// Therefore we need to read the config again if the type has changed |
|
52
|
12 |
|
if ($cls->name !== \get_class($subject)) { |
|
53
|
4 |
|
$config = $this->entityConfigLookUp->getEntityConfig(new \ReflectionClass($subject)); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
// populate the result |
|
57
|
12 |
|
$this->populate($subject, $data, $config); |
|
58
|
|
|
|
|
59
|
12 |
|
return $subject; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
12 |
|
private function populate($subject, $data, EntityConfig $config) |
|
63
|
|
|
{ |
|
64
|
|
|
// get the properties we need to map |
|
65
|
12 |
|
$entries = $config->getMarkedProperties(); |
|
66
|
|
|
|
|
67
|
12 |
|
foreach ($entries as $entry) { |
|
68
|
|
|
// awake using the alias name |
|
69
|
12 |
|
$alias = $entry->alias; |
|
70
|
|
|
|
|
71
|
|
|
// do we have data for that property |
|
72
|
12 |
|
if (isset($data[$alias])) { |
|
73
|
10 |
|
$entry->propertyAccess->set( |
|
74
|
10 |
|
$subject, |
|
75
|
12 |
|
$entry->mapper->awake($this, $data[$alias]) |
|
76
|
|
|
); |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
12 |
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|