ValuesFinder::findFromSnaks()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 20
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 5

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 8
c 1
b 0
f 0
nc 4
nop 2
dl 0
loc 20
ccs 11
cts 11
cp 1
crap 5
rs 9.6111
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