1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types = 1); |
4
|
|
|
|
5
|
|
|
namespace Stratadox\Hydrator; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Delegates hydration, selecting a hydrator based on an input value. |
9
|
|
|
* |
10
|
|
|
* @package Stratadox\Hydrate |
11
|
|
|
* @author Stratadox |
12
|
|
|
*/ |
13
|
|
|
final class OneOfTheseHydrators implements Hydrates |
14
|
|
|
{ |
15
|
|
|
private $decisionKey; |
16
|
|
|
private $hydratorMap; |
17
|
|
|
|
18
|
|
|
private function __construct(string $decisionKey, array $hydratorMap) |
19
|
|
|
{ |
20
|
|
|
$this->decisionKey = $decisionKey; |
21
|
|
|
$this->hydratorMap = $hydratorMap; |
22
|
|
|
foreach ($hydratorMap as $key => $instance) { |
23
|
|
|
$this->mustBeAString($key); |
24
|
|
|
$this->mustBeAHydrator($instance); |
25
|
|
|
} |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* Creates a new selective hydrator. |
30
|
|
|
* |
31
|
|
|
* @param string $key The key in which the decision key is stored. |
32
|
|
|
* @param array $map Map of hydrators as [string $key => Hydrates $hydrator]. |
33
|
|
|
* @return self The delegating hydrator. |
34
|
|
|
*/ |
35
|
|
|
public static function decideBasedOnThe(string $key, array $map) : self |
36
|
|
|
{ |
37
|
|
|
return new self($key, $map); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
/** @inheritdoc */ |
41
|
|
|
public function fromArray(array $input) |
42
|
|
|
{ |
43
|
|
|
return $this->hydrateAnInstanceUsing( |
44
|
|
|
$this->hydratorBasedOn($this->keyFromThe($input)), |
45
|
|
|
$input |
46
|
|
|
); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
private function hydrateAnInstanceUsing(Hydrates $hydrator, array $input) |
50
|
|
|
{ |
51
|
|
|
return $hydrator->fromArray($input); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** @throws CouldNotHydrate */ |
55
|
|
|
private function hydratorBasedOn(string $key) : Hydrates |
56
|
|
|
{ |
57
|
|
|
if (!isset($this->hydratorMap[$key])) { |
58
|
|
|
throw CannotDecideOnAHydrator::withThis($key); |
59
|
|
|
} |
60
|
|
|
return $this->hydratorMap[$key]; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
/** @throws CouldNotHydrate */ |
64
|
|
|
private function keyFromThe(array $input) : string |
65
|
|
|
{ |
66
|
|
|
if (!isset($input[$this->decisionKey])) { |
67
|
|
|
throw CannotDecideOnAHydrator::without($this->decisionKey); |
68
|
|
|
} |
69
|
|
|
return $input[$this->decisionKey]; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
private function mustBeAString(string $key) : void {} |
|
|
|
|
73
|
|
|
private function mustBeAHydrator(Hydrates $instance) : void {} |
|
|
|
|
74
|
|
|
} |
75
|
|
|
|
This check looks for parameters that have been defined for a function or method, but which are not used in the method body.