1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace GFG\DTOContext\Factory; |
4
|
|
|
|
5
|
|
|
use GFG\DTOContext\DataWrapper; |
6
|
|
|
|
7
|
|
|
abstract class Base implements FactoryInterface |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* @var HydratorInterface |
11
|
|
|
*/ |
12
|
|
|
private static $hydrator; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* @return array |
16
|
|
|
*/ |
17
|
|
|
abstract public function getMappingList(); |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* {@inheritdoc} |
21
|
|
|
*/ |
22
|
|
|
public function build( |
23
|
|
|
$contextName, |
24
|
|
|
DataWrapper\DataWrapperInterface $dataWrapper |
25
|
|
|
) { |
26
|
|
|
$contextClass = $this->getMappedContext($contextName); |
27
|
|
|
return new $contextClass($dataWrapper); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* {@inheritdoc} |
32
|
|
|
*/ |
33
|
|
|
public function rebuild(array $rawData, HydratorInterface $hydrator) |
34
|
|
|
{ |
35
|
|
|
$hydrator->validateRawData($rawData); |
36
|
|
|
$this->checkMappedContext($rawData['name']); |
37
|
|
|
|
38
|
|
|
$dataWrapperName = $rawData['data_wrapper']; |
39
|
|
|
|
40
|
|
|
$context = $this->build( |
41
|
|
|
$rawData['name'], |
42
|
|
|
new $dataWrapperName($rawData['data']) |
43
|
|
|
); |
44
|
|
|
|
45
|
|
|
$hydrator->hydrate($context, $rawData); |
46
|
|
|
|
47
|
|
|
return $context; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* Return the mapped context class |
52
|
|
|
* |
53
|
|
|
* @param string $contextName |
54
|
|
|
* @return string |
55
|
|
|
*/ |
56
|
|
|
protected function getMappedContext($contextName) |
57
|
|
|
{ |
58
|
|
|
$this->checkMappedContext($contextName); |
59
|
|
|
$mappingList = $this->getMappingList(); |
60
|
|
|
|
61
|
|
|
return $mappingList[$contextName]; |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* Test a mapped context |
66
|
|
|
* |
67
|
|
|
* @param string $contextName |
68
|
|
|
* @return void |
69
|
|
|
*/ |
70
|
|
|
protected function checkMappedContext($contextName) |
71
|
|
|
{ |
72
|
|
|
if (!array_key_exists($contextName, $this->getMappingList())) { |
73
|
|
|
throw new \InvalidArgumentException("invalid context name {$contextName}"); |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* @return HydratorInterface |
79
|
|
|
*/ |
80
|
|
|
public function getHydrator() |
81
|
|
|
{ |
82
|
|
|
if (!self::$hydrator) { |
83
|
|
|
self::$hydrator = new Hydrator(); |
84
|
|
|
} |
85
|
|
|
|
86
|
|
|
return self::$hydrator; |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
/** |
90
|
|
|
* @param HydratorInterface $hydrator |
91
|
|
|
* @return Base |
92
|
|
|
*/ |
93
|
|
|
public function setHydrator(HydratorInterface $hydrator) |
94
|
|
|
{ |
95
|
|
|
self::$hydrator = $hydrator; |
96
|
|
|
return $this; |
97
|
|
|
} |
98
|
|
|
} |
99
|
|
|
|