Completed
Push — detect-covers-fails ( bd35c8...c3f051 )
by no
16:27 queued 12:25
created

DispatchingEntityIdParser   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 72
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 9
c 1
b 0
f 0
lcom 1
cbo 1
dl 0
loc 72
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A parse() 0 17 4
A assertIdIsString() 0 5 2
A buildId() 0 8 2
1
<?php
2
3
namespace Wikibase\DataModel\Entity;
4
5
use InvalidArgumentException;
6
7
/**
8
 * @since 4.2
9
 *
10
 * @licence GNU GPL v2+
11
 * @author Jeroen De Dauw < [email protected] >
12
 */
13
class DispatchingEntityIdParser implements EntityIdParser {
14
15
	/**
16
	 * @var callable[]
17
	 */
18
	private $idBuilders;
19
20
	/**
21
	 * Takes an array in which each key is a preg_match pattern.
22
	 * The first pattern the id matches against will be picked.
23
	 * The value this key points to has to be a builder function
24
	 * that takes as only required argument the id serialization
25
	 * (string) and returns an EntityId instance.
26
	 *
27
	 * @param callable[] $idBuilders
28
	 */
29
	public function __construct( array $idBuilders ) {
30
		$this->idBuilders = $idBuilders;
31
	}
32
33
	/**
34
	 * @param string $idSerialization
35
	 *
36
	 * @throws EntityIdParsingException
37
	 * @return EntityId
38
	 */
39
	public function parse( $idSerialization ) {
40
		$this->assertIdIsString( $idSerialization );
41
42
		if ( empty( $this->idBuilders ) ) {
43
			throw new EntityIdParsingException( 'No id builders are configured' );
44
		}
45
46
		foreach ( $this->idBuilders as $idPattern => $idBuilder ) {
47
			if ( preg_match( $idPattern, $idSerialization ) ) {
48
				return $this->buildId( $idBuilder, $idSerialization );
49
			}
50
		}
51
52
		throw new EntityIdParsingException(
53
			"The serialization \"$idSerialization\" is not recognized by the configured id builders"
54
		);
55
	}
56
57
	/**
58
	 * @param string $idSerialization
59
	 *
60
	 * @throws EntityIdParsingException
61
	 */
62
	private function assertIdIsString( $idSerialization ) {
63
		if ( !is_string( $idSerialization ) ) {
64
			throw new EntityIdParsingException( '$idSerialization must be a string' );
65
		}
66
	}
67
68
	/**
69
	 * @param callable $idBuilder
70
	 * @param string $idSerialization
71
	 *
72
	 * @throws EntityIdParsingException
73
	 * @return EntityId
74
	 */
75
	private function buildId( $idBuilder, $idSerialization ) {
76
		try {
77
			return call_user_func( $idBuilder, $idSerialization );
78
		} catch ( InvalidArgumentException $ex ) {
79
			// Should not happen, but if it does, re-throw the original message
80
			throw new EntityIdParsingException( $ex->getMessage() );
81
		}
82
	}
83
84
}
85