Passed
Pull Request — master (#182)
by
unknown
02:22
created

EntityIdComposer   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 0
Metric Value
wmc 8
lcom 1
cbo 0
dl 0
loc 50
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 9 5
A composeEntityId() 0 13 3
1
<?php
2
3
namespace Wikibase\DataModel\Services\EntityId;
4
5
use InvalidArgumentException;
6
use UnexpectedValueException;
7
use Wikibase\DataModel\Entity\EntityId;
8
9
/**
10
 * Constructs EntityId objects from entity type identifiers and unique parts of entity ID
11
 * serializations. The unique part is typically the numeric part of an entity ID, excluding the
12
 * static part that's the same for all IDs of that type.
13
 *
14
 * Meant to be the counterpart for @see Int32EntityId::getNumericId, as well as an extensible
15
 * replacement for @see LegacyIdInterpreter::newIdFromTypeAndNumber.
16
 *
17
 * @license GPL-2.0+
18
 * @author Thiemo Mättig
19
 */
20
class EntityIdComposer {
21
22
	/**
23
	 * @var callable[]
24
	 */
25
	private $composers;
26
27
	/**
28
	 * @param callable[] $composers Array mapping entity type identifiers to callables accepting a
29
	 *  single mixed value, representing the unique part of an entity ID serialization, and
30
	 *  returning an EntityId object.
31
	 *
32
	 * @throws InvalidArgumentException
33
	 */
34
	public function __construct( array $composers ) {
35
		foreach ( $composers as $entityType => $composer ) {
36
			if ( !is_string( $entityType ) || $entityType === '' || !is_callable( $composer ) ) {
37
				throw new InvalidArgumentException( '$composers must map non-empty strings to callables' );
38
			}
39
		}
40
41
		$this->composers = $composers;
42
	}
43
44
	/**
45
	 * @param string $repositoryName
46
	 * @param string $entityType
47
	 * @param mixed $uniquePart
48
	 *
49
	 * @throws InvalidArgumentException when the entity type is not known or the unique part is not
50
	 *  unique.
51
	 * @throws UnexpectedValueException when the configured composer did not return an EntityId
52
	 *  object.
53
	 * @return EntityId
54
	 */
55
	public function composeEntityId( $repositoryName, $entityType, $uniquePart ) {
56
		if ( !isset( $this->composers[$entityType] ) ) {
57
			throw new InvalidArgumentException( 'Unknown entity type ' . $entityType );
58
		}
59
60
		$id = $this->composers[$entityType]( $repositoryName, $uniquePart );
61
62
		if ( !( $id instanceof EntityId ) ) {
63
			throw new UnexpectedValueException( 'Composer for ' . $entityType . ' is invalid' );
64
		}
65
66
		return $id;
67
	}
68
69
}
70