|
1
|
|
|
<?php |
|
2
|
|
|
declare(strict_types=1); |
|
3
|
|
|
|
|
4
|
|
|
namespace Stratadox\Deserializer; |
|
5
|
|
|
|
|
6
|
|
|
use Stratadox\ImmutableCollection\ImmutableCollection; |
|
7
|
|
|
|
|
8
|
|
|
/** |
|
9
|
|
|
* Uses one of several deserialization options to deserialize the input array |
|
10
|
|
|
* into objects. |
|
11
|
|
|
* |
|
12
|
|
|
* @author Stratadox |
|
13
|
|
|
*/ |
|
14
|
|
|
final class OneOfThese extends ImmutableCollection implements Deserializer |
|
15
|
|
|
{ |
|
16
|
|
|
private function __construct(DeserializationOption ...$options) |
|
17
|
|
|
{ |
|
18
|
|
|
parent::__construct(...$options); |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* Makes a new collection of deserialization options. |
|
23
|
|
|
* |
|
24
|
|
|
* @param DeserializationOption ...$options The options to consider when |
|
25
|
|
|
* deserializing an input array. |
|
26
|
|
|
* @return Deserializer The deserialization options. |
|
27
|
|
|
*/ |
|
28
|
|
|
public static function deserializers(DeserializationOption ...$options): Deserializer |
|
29
|
|
|
{ |
|
30
|
|
|
return new OneOfThese(...$options); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
|
|
34
|
|
|
/** @inheritdoc */ |
|
35
|
|
|
public function current(): DeserializationOption |
|
36
|
|
|
{ |
|
37
|
|
|
return parent::current(); |
|
38
|
|
|
} |
|
39
|
|
|
|
|
40
|
|
|
/** @inheritdoc */ |
|
41
|
|
|
public function from(array $input) |
|
42
|
|
|
{ |
|
43
|
|
|
return $this->makeFrom($input, $this->optionFor($input)); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
|
|
/** @inheritdoc */ |
|
47
|
|
|
public function typeFor(array $input): string |
|
48
|
|
|
{ |
|
49
|
|
|
return $this->wouldProduceFor($input, $this->optionFor($input)); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
/** |
|
53
|
|
|
* @throws DeserializationFailure |
|
54
|
|
|
* @return mixed |
|
55
|
|
|
*/ |
|
56
|
|
|
private function makeFrom(array $input, DeserializationOption $deserialize) |
|
57
|
|
|
{ |
|
58
|
|
|
return $deserialize->from($input); |
|
59
|
|
|
} |
|
60
|
|
|
|
|
61
|
|
|
/** @throws DeserializationFailure */ |
|
62
|
|
|
private function wouldProduceFor(array $input, DeserializationOption $deserialize): string |
|
63
|
|
|
{ |
|
64
|
|
|
return $deserialize->typeFor($input); |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
/** @throws DeserializationFailure */ |
|
68
|
|
|
private function optionFor(array $input): DeserializationOption |
|
69
|
|
|
{ |
|
70
|
|
|
foreach ($this as $option) { |
|
71
|
|
|
if ($option->isSatisfiedBy($input)) { |
|
72
|
|
|
return $option; |
|
73
|
|
|
} |
|
74
|
|
|
} |
|
75
|
|
|
throw UnacceptableInput::illegal($input); |
|
76
|
|
|
} |
|
77
|
|
|
} |
|
78
|
|
|
|