1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Deserializers; |
4
|
|
|
|
5
|
|
|
use Deserializers\Exceptions\InvalidAttributeException; |
6
|
|
|
use Deserializers\Exceptions\MissingAttributeException; |
7
|
|
|
use Deserializers\Exceptions\MissingTypeException; |
8
|
|
|
use Deserializers\Exceptions\UnsupportedTypeException; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* @since 1.0 |
12
|
|
|
* |
13
|
|
|
* @license GPL-2.0+ |
14
|
|
|
* @author Jeroen De Dauw < [email protected] > |
15
|
|
|
*/ |
16
|
|
|
abstract class TypedObjectDeserializer implements DispatchableDeserializer { |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var string |
20
|
|
|
*/ |
21
|
|
|
private $objectType; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @var string |
25
|
|
|
*/ |
26
|
|
|
private $typeKey; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param string $objectType |
30
|
|
|
* @param string $typeKey |
31
|
|
|
*/ |
32
|
3 |
|
public function __construct( $objectType, $typeKey = 'objectType' ) { |
33
|
3 |
|
$this->objectType = $objectType; |
34
|
3 |
|
$this->typeKey = $typeKey; |
35
|
|
|
|
36
|
3 |
|
} |
37
|
|
|
|
38
|
|
|
protected function assertCanDeserialize( $serialization ) { |
39
|
|
|
if ( !$this->hasObjectType( $serialization ) ) { |
40
|
|
|
throw new MissingTypeException(); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
if ( !$this->hasCorrectObjectType( $serialization ) ) { |
44
|
|
|
throw new UnsupportedTypeException( $serialization[$this->typeKey] ); |
45
|
|
|
} |
46
|
|
|
} |
47
|
|
|
|
48
|
3 |
|
public function isDeserializerFor( $serialization ) { |
49
|
3 |
|
return $this->hasObjectType( $serialization ) && $this->hasCorrectObjectType( $serialization ); |
50
|
|
|
} |
51
|
|
|
|
52
|
2 |
|
private function hasCorrectObjectType( $serialization ) { |
53
|
2 |
|
return $serialization[$this->typeKey] === $this->objectType; |
54
|
|
|
} |
55
|
|
|
|
56
|
3 |
|
private function hasObjectType( $serialization ) { |
57
|
3 |
|
return is_array( $serialization ) |
58
|
3 |
|
&& array_key_exists( $this->typeKey, $serialization ); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
protected function requireAttribute( array $array, $attributeName ) { |
62
|
|
|
if ( !array_key_exists( $attributeName, $array ) ) { |
63
|
|
|
throw new MissingAttributeException( |
64
|
|
|
$attributeName |
65
|
|
|
); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|
69
|
|
|
protected function assertAttributeIsArray( array $array, $attributeName ) { |
70
|
|
|
$this->assertAttributeInternalType( $array, $attributeName, 'array' ); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
protected function assertAttributeInternalType( array $array, $attributeName, $internalType ) { |
74
|
|
|
if ( gettype( $array[$attributeName] ) !== $internalType ) { |
75
|
|
|
throw new InvalidAttributeException( |
76
|
|
|
$attributeName, |
77
|
|
|
$array[$attributeName], |
78
|
|
|
"The internal type of attribute '$attributeName' needs to be '$internalType'" |
79
|
|
|
); |
80
|
|
|
} |
81
|
|
|
} |
82
|
|
|
|
83
|
|
|
} |
84
|
|
|
|