1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Wikibase\DataModel\Services\DataValue; |
4
|
|
|
|
5
|
|
|
use DataValues\DataValue; |
6
|
|
|
use Wikibase\DataModel\Entity\PropertyId; |
7
|
|
|
use Wikibase\DataModel\Services\Lookup\PropertyDataTypeLookup; |
8
|
|
|
use Wikibase\DataModel\Services\Lookup\PropertyDataTypeLookupException; |
9
|
|
|
use Wikibase\DataModel\Snak\PropertyValueSnak; |
10
|
|
|
use Wikibase\DataModel\Snak\Snak; |
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Find all data values for a specified data type in an array of snaks. |
14
|
|
|
* |
15
|
|
|
* @since 1.1 |
16
|
|
|
* |
17
|
|
|
* @license GPL-2.0-or-later |
18
|
|
|
* @author Bene* < [email protected] > |
19
|
|
|
*/ |
20
|
|
|
class ValuesFinder { |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @var PropertyDataTypeLookup |
24
|
|
|
*/ |
25
|
|
|
private $propertyDataTypeLookup; |
26
|
|
|
|
27
|
10 |
|
public function __construct( PropertyDataTypeLookup $propertyDataTypeLookup ) { |
28
|
10 |
|
$this->propertyDataTypeLookup = $propertyDataTypeLookup; |
29
|
10 |
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Find all data values for the specified data type in the array of snaks. |
33
|
|
|
* |
34
|
|
|
* @param Snak[] $snaks |
35
|
|
|
* @param string $dataType |
36
|
|
|
* |
37
|
|
|
* @return DataValue[] |
38
|
|
|
*/ |
39
|
10 |
|
public function findFromSnaks( array $snaks, $dataType ) { |
40
|
10 |
|
$found = []; |
41
|
|
|
|
42
|
10 |
|
foreach ( $snaks as $snak ) { |
43
|
9 |
|
if ( $snak instanceof PropertyValueSnak && |
44
|
7 |
|
$this->isMatchingDataType( $snak->getPropertyId(), $dataType ) |
45
|
9 |
|
) { |
46
|
4 |
|
$dataValue = $snak->getDataValue(); |
47
|
4 |
|
if ( method_exists( $dataValue, 'getHash' ) ) { |
48
|
4 |
|
// We can only tag values as found that are |
49
|
10 |
|
// hashable. DataValueObject should, but `getDataValue` |
50
|
|
|
// only returns the `DataValue` interface, which doesn't |
51
|
10 |
|
// define `getHash` |
52
|
|
|
// @phan-suppress-next-line PhanUndeclaredMethod |
53
|
|
|
$found[$dataValue->getHash()] = $dataValue; |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
return $found; |
59
|
|
|
} |
60
|
7 |
|
|
61
|
|
|
/** |
62
|
7 |
|
* @param PropertyId $propertyId |
63
|
1 |
|
* @param string $dataType |
64
|
1 |
|
* |
65
|
|
|
* @return bool |
66
|
|
|
*/ |
67
|
|
|
private function isMatchingDataType( PropertyId $propertyId, $dataType ) { |
68
|
|
|
try { |
69
|
|
|
return $this->propertyDataTypeLookup->getDataTypeIdForProperty( $propertyId ) === $dataType; |
70
|
|
|
} catch ( PropertyDataTypeLookupException $ex ) { |
71
|
|
|
return false; |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
} |
76
|
|
|
|