1 | <?php |
||
2 | |||
3 | namespace Wikibase\DataModel\Services\Statement; |
||
4 | |||
5 | use Wikibase\DataModel\Entity\EntityIdParser; |
||
6 | use Wikibase\DataModel\Entity\EntityIdParsingException; |
||
7 | use Wikibase\DataModel\Statement\StatementGuid; |
||
8 | |||
9 | /** |
||
10 | * @since 1.1 |
||
11 | * |
||
12 | * @license GPL-2.0-or-later |
||
13 | * @author Katie Filbert < [email protected] > |
||
14 | */ |
||
15 | class StatementGuidValidator { |
||
16 | |||
17 | /** |
||
18 | * @var EntityIdParser |
||
19 | */ |
||
20 | private $entityIdParser; |
||
21 | |||
22 | public function __construct( EntityIdParser $entityIdParser ) { |
||
23 | $this->entityIdParser = $entityIdParser; |
||
24 | } |
||
25 | 30 | ||
26 | 30 | /** |
|
27 | 30 | * Validates a statement guid |
|
28 | * |
||
29 | * @since 0.4 |
||
30 | * |
||
31 | * @param string $guid |
||
32 | * |
||
33 | * @return bool |
||
34 | */ |
||
35 | public function validate( $guid ) { |
||
36 | if ( !$this->validateFormat( $guid ) ) { |
||
37 | return false; |
||
38 | 30 | } |
|
39 | 30 | ||
40 | 9 | $guidParts = explode( StatementGuid::SEPARATOR, $guid ); |
|
41 | |||
42 | if ( !$this->validateStatementGuidPrefix( $guidParts[0] ) || !$this->validateGuid( $guidParts[1] ) ) { |
||
43 | 21 | return false; |
|
44 | } |
||
45 | 21 | ||
46 | 9 | return true; |
|
47 | } |
||
48 | |||
49 | 12 | /** |
|
50 | * Basic validation for statement guid format |
||
51 | * |
||
52 | * @since 0.4 |
||
53 | * |
||
54 | * @param string $guid |
||
55 | * |
||
56 | * @return bool |
||
57 | */ |
||
58 | public function validateFormat( $guid ) { |
||
59 | if ( !is_string( $guid ) ) { |
||
0 ignored issues
–
show
introduced
by
![]() |
|||
60 | return false; |
||
61 | 30 | } |
|
62 | 30 | ||
63 | 1 | $keyParts = explode( '$', $guid ); |
|
64 | |||
65 | if ( count( $keyParts ) !== 2 ) { |
||
66 | 29 | return false; |
|
67 | } |
||
68 | 29 | ||
69 | 8 | return true; |
|
70 | } |
||
71 | |||
72 | 21 | /** |
|
73 | * Validate the second part of a statement guid, after the $ |
||
74 | * |
||
75 | * @since 0.4 |
||
76 | * |
||
77 | * @param string $guid |
||
78 | * |
||
79 | * @return bool |
||
80 | */ |
||
81 | private function validateGuid( $guid ) { |
||
82 | return (bool)preg_match( |
||
83 | '/^\{?[A-Z\d]{8}-[A-Z\d]{4}-[A-Z\d]{4}-[A-Z\d]{4}-[A-Z\d]{12}\}?\z/i', |
||
84 | 19 | $guid |
|
85 | 19 | ); |
|
86 | } |
||
87 | 19 | ||
88 | 7 | /** |
|
89 | * Validate the statement guid prefix is a valid entity id |
||
90 | * |
||
91 | 12 | * @since 0.4 |
|
92 | * |
||
93 | * @param string $prefixedId |
||
94 | * |
||
95 | * @return bool |
||
96 | */ |
||
97 | private function validateStatementGuidPrefix( $prefixedId ) { |
||
98 | try { |
||
99 | $this->entityIdParser->parse( $prefixedId ); |
||
100 | return true; |
||
101 | } catch ( EntityIdParsingException $ex ) { |
||
102 | return false; |
||
103 | 21 | } |
|
104 | } |
||
105 | 21 | ||
106 | } |
||
107 |