1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Wikibase\DataModel\Services\EntityId; |
4
|
|
|
|
5
|
|
|
use Wikibase\DataModel\Entity\EntityId; |
6
|
|
|
use Wikibase\DataModel\Entity\EntityIdParser; |
7
|
|
|
use Wikibase\DataModel\Entity\EntityIdParsingException; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* EntityIdParser that strips a fixed prefix and parses the remaining suffix as an EntityId. |
11
|
|
|
* This can be used to parse entity URIs into EntityId objects. |
12
|
|
|
* |
13
|
|
|
* @since 1.1 |
14
|
|
|
* |
15
|
|
|
* @license GPL-2.0+ |
16
|
|
|
* @author Daniel Kinzler |
17
|
|
|
*/ |
18
|
|
|
class PrefixedEntityIdParser implements EntityIdParser { |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @var string |
22
|
|
|
*/ |
23
|
|
|
private $prefix; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @var EntityIdParser |
27
|
|
|
*/ |
28
|
|
|
private $idParser; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @param string $prefix The prefix to be stripped. Stripping is case sensitive. |
32
|
|
|
* @param EntityIdParser $idParser |
33
|
|
|
*/ |
34
|
|
|
public function __construct( $prefix, EntityIdParser $idParser ) { |
35
|
|
|
$this->prefix = $prefix; |
36
|
|
|
$this->idParser = $idParser; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* Parses the given string into an EntityId by first stripping a fixed prefix. |
41
|
|
|
* If the string does not start with the expected prefix, an EntityIdParsingException |
42
|
|
|
* is thrown. |
43
|
|
|
* |
44
|
|
|
* @param string $idSerialization An entity ID with some prefix attached, e.g. an entity URI. |
45
|
|
|
* |
46
|
|
|
* @throws EntityIdParsingException If the string does not start with the expected prefix, |
47
|
|
|
* or the remaining suffix is not a valid entity ID string. |
48
|
|
|
* @return EntityId |
49
|
|
|
*/ |
50
|
|
|
public function parse( $idSerialization ) { |
51
|
|
|
$prefixLength = strlen( $this->prefix ); |
52
|
|
|
|
53
|
|
|
if ( strncmp( $idSerialization, $this->prefix, $prefixLength ) !== 0 ) { |
54
|
|
|
throw new EntityIdParsingException( 'Missing expected prefix "' . $this->prefix |
55
|
|
|
. '" in "' . $idSerialization . '"' ); |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
$idSerialization = substr( $idSerialization, $prefixLength ); |
59
|
|
|
return $this->idParser->parse( $idSerialization ); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
} |
63
|
|
|
|