-
Notifications
You must be signed in to change notification settings - Fork 6
/
DataTypeStatementGrouper.php
100 lines (84 loc) · 2.48 KB
/
DataTypeStatementGrouper.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?php
namespace Wikibase\DataModel\Services\Statement\Grouper;
use Wikibase\DataModel\Services\Lookup\PropertyDataTypeLookup;
use Wikibase\DataModel\Services\Lookup\PropertyDataTypeLookupException;
use Wikibase\DataModel\Statement\Statement;
use Wikibase\DataModel\Statement\StatementList;
/**
* @since 3.2
*
* @licence GNU GPL v2+
* @author Thiemo Mättig
*/
class DataTypeStatementGrouper implements StatementGrouper {
/**
* @var PropertyDataTypeLookup
*/
private $dataTypeLookup;
/**
* @var StatementList[]
*/
private $groups = array();
/**
* @var string[] An associative array, mapping data type identifiers to statement group
* identifiers.
*/
private $groupIdentifiers = array();
/**
* @var string
*/
private $defaultGroupIdentifier = 'statements';
/**
* @param PropertyDataTypeLookup $dataTypeLookup
* @param array $groupDefinitions An associative array, mapping statement group identifiers to
* either arrays of data type identifiers, or to null for the default group.
*/
public function __construct(
PropertyDataTypeLookup $dataTypeLookup,
array $groupDefinitions = array()
) {
$this->dataTypeLookup = $dataTypeLookup;
$this->setGroupDefinitions( $groupDefinitions );
}
private function setGroupDefinitions( array $groupDefinitions ) {
foreach ( $groupDefinitions as $key => $dataTypes ) {
$this->groups[$key] = new StatementList();
if ( $dataTypes === null ) {
$this->defaultGroupIdentifier = $key;
} else {
foreach ( (array)$dataTypes as $dataType ) {
$this->groupIdentifiers[$dataType] = $key;
}
}
}
}
/**
* @param StatementList $statements
*
* @return StatementList[] An associative array, mapping statement group identifiers to
* StatementList objects.
*/
public function groupStatements( StatementList $statements ) {
foreach ( $statements->toArray() as $statement ) {
$key = $this->getGroupIdentifier( $statement );
$this->groups[$key]->addStatement( $statement );
}
return $this->groups;
}
/**
* @param Statement $statement
*
* @return string Statement group identifier
*/
private function getGroupIdentifier( Statement $statement ) {
$id = $statement->getPropertyId();
try {
$dataType = $this->dataTypeLookup->getDataTypeIdForProperty( $id );
} catch ( PropertyDataTypeLookupException $ex ) {
return $this->defaultGroupIdentifier;
}
return isset( $this->groupIdentifiers[$dataType] )
? $this->groupIdentifiers[$dataType]
: $this->defaultGroupIdentifier;
}
}