Passed
Push — dispatchable ( 7936d7...03d6f2 )
by no
08:11 queued 05:11
created

EntityDeserializer::isDeserializerFor()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 2
eloc 3
nc 2
nop 1
1
<?php
2
3
namespace Wikibase\InternalSerialization\Deserializers;
4
5
use Deserializers\DispatchableDeserializer;
6
use Deserializers\Exceptions\DeserializationException;
7
use Wikibase\DataModel\Entity\EntityDocument;
8
9
/**
10
 * @licence GNU GPL v2+
11
 * @author Jeroen De Dauw < [email protected] >
12
 * @author Thiemo Mättig
13
 */
14
class EntityDeserializer implements DispatchableDeserializer {
15
16
	/**
17
	 * @var DispatchableDeserializer
18
	 */
19
	private $legacyDeserializer;
20
21
	/**
22
	 * @var DispatchableDeserializer
23
	 */
24
	private $currentDeserializer;
25
26
	public function __construct(
27
		DispatchableDeserializer $legacyDeserializer,
28
		DispatchableDeserializer $currentDeserializer
29
	) {
30
		$this->legacyDeserializer = $legacyDeserializer;
31
		$this->currentDeserializer = $currentDeserializer;
32
	}
33
34
	/**
35
	 * @param array $serialization
36
	 *
37
	 * @return EntityDocument
38
	 * @throws DeserializationException
39
	 */
40
	public function deserialize( $serialization ) {
41
		if ( !is_array( $serialization ) ) {
42
			throw new DeserializationException( 'Entity serialization must be an array' );
43
		}
44
45
		if ( $this->currentDeserializer->isDeserializerFor( $serialization ) ) {
46
			return $this->currentDeserializer->deserialize( $serialization );
47
		} elseif ( $this->legacyDeserializer->isDeserializerFor( $serialization ) ) {
48
			return $this->legacyDeserializer->deserialize( $serialization );
49
		} else {
50
			return $this->fromUnknownSerialization( $serialization );
51
		}
52
	}
53
54
	private function fromUnknownSerialization( array $serialization ) {
55
		try {
56
			return $this->currentDeserializer->deserialize( $serialization );
57
		} catch ( DeserializationException $currentEx ) {
58
			try {
59
				return $this->legacyDeserializer->deserialize( $serialization );
60
			} catch ( DeserializationException $legacyEx ) {
61
				throw new DeserializationException(
62
					'The provided entity serialization is neither legacy ('
63
					. $legacyEx->getMessage() . ') nor current ('
64
					. $currentEx->getMessage() . ')'
65
				);
66
			}
67
		}
68
	}
69
70
	/**
71
	 * @see DispatchableDeserializer::isDeserializerFor
72
	 *
73
	 * @since 2.2
74
	 *
75
	 * @param mixed $serialization
76
	 *
77
	 * @return bool
78
	 */
79
	public function isDeserializerFor( $serialization ) {
80
		return $this->currentDeserializer->isDeserializerFor( $serialization )
81
			|| $this->legacyDeserializer->isDeserializerFor( $serialization );
82
	}
83
84
}
85