Completed
Push — deprecated ( 36e613 )
by
unknown
08:46 queued 43s
created

TypedObjectDeserializer::requireAttribute()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 2
ccs 0
cts 0
cp 0
crap 6
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-or-later
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
	public function __construct( $objectType, $typeKey = 'objectType' ) {
33
		$this->objectType = $objectType;
34
		$this->typeKey = $typeKey;
35
	}
36
37
	protected function assertCanDeserialize( $serialization ) {
38
		if ( !$this->hasObjectType( $serialization ) ) {
39
			throw new MissingTypeException();
40
		}
41
42
		if ( !$this->hasCorrectObjectType( $serialization ) ) {
43
			throw new UnsupportedTypeException( $serialization[$this->typeKey] );
44
		}
45
	}
46
47
	public function isDeserializerFor( $serialization ) {
48
		return $this->hasObjectType( $serialization ) && $this->hasCorrectObjectType( $serialization );
49
	}
50
51
	private function hasCorrectObjectType( array $serialization ) {
52
		return $serialization[$this->typeKey] === $this->objectType;
53
	}
54
55
	private function hasObjectType( $serialization ) {
56
		return is_array( $serialization )
57
			&& array_key_exists( $this->typeKey, $serialization );
58
	}
59
60
}
61