Completed
Pull Request — master (#99)
by no
07:33 queued 04:56
created

LegacyEntityIdDeserializer::isDeserializerFor()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 6
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
rs 9.2
cc 4
eloc 5
nc 4
nop 1
1
<?php
2
3
namespace Wikibase\InternalSerialization\Deserializers;
4
5
use Deserializers\DispatchableDeserializer;
6
use Deserializers\Exceptions\DeserializationException;
7
use InvalidArgumentException;
8
use Wikibase\DataModel\Entity\EntityId;
9
use Wikibase\DataModel\LegacyIdInterpreter;
10
use Wikibase\DataModel\Entity\EntityIdParser;
11
use Wikibase\DataModel\Entity\EntityIdParsingException;
12
13
/**
14
 * @licence GNU GPL v2+
15
 * @author Jeroen De Dauw < [email protected] >
16
 */
17
class LegacyEntityIdDeserializer implements DispatchableDeserializer {
18
19
	/**
20
	 * @var EntityIdParser
21
	 */
22
	private $idParser;
23
24
	public function __construct( EntityIdParser $idParser ) {
25
		$this->idParser = $idParser;
26
	}
27
28
	/**
29
	 * @param string|array $serialization
30
	 *
31
	 * @return EntityId
32
	 * @throws DeserializationException
33
	 */
34
	public function deserialize( $serialization ) {
35
		if ( is_string( $serialization ) ) {
36
			return $this->getParsedId( $serialization );
37
		}
38
		elseif ( $this->isDeserializerFor( $serialization ) ) {
39
			return $this->getIdFromLegacyFormat( $serialization );
40
		}
41
		else {
42
			throw new DeserializationException( 'Entity id format not recognized' );
43
		}
44
	}
45
46
	/**
47
	 * @param string $serialization
48
	 *
49
	 * @throws DeserializationException
50
	 * @return EntityId
51
	 */
52
	private function getParsedId( $serialization ) {
53
		try {
54
			return $this->idParser->parse( $serialization );
55
		}
56
		catch ( EntityIdParsingException $ex ) {
57
			throw new DeserializationException( $ex->getMessage(), $ex );
58
		}
59
	}
60
61
	private function getIdFromLegacyFormat( array $serialization ) {
62
		try {
63
			return LegacyIdInterpreter::newIdFromTypeAndNumber( $serialization[0], $serialization[1] );
64
		}
65
		catch ( InvalidArgumentException $ex ) {
66
			throw new DeserializationException( $ex->getMessage(), $ex );
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 is_array( $serialization )
81
			&& count( $serialization ) === 2
82
			&& array_key_exists( 0, $serialization )
83
			&& array_key_exists( 1, $serialization );
84
	}
85
86
}
87