-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathTemplateSegment.php
More file actions
90 lines (70 loc) · 2.38 KB
/
TemplateSegment.php
File metadata and controls
90 lines (70 loc) · 2.38 KB
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
<?php
declare( strict_types = 1 );
namespace ProfessionalWiki\AutomatedValues\Domain;
use DataValues\DataValue;
use DataValues\StringValue;
use Wikibase\DataModel\Entity\PropertyId;
use Wikibase\DataModel\Snak\PropertyValueSnak;
use Wikibase\DataModel\Snak\Snak;
use Wikibase\DataModel\Statement\Statement;
use Wikibase\DataModel\Statement\StatementList;
class TemplateSegment {
private string $template;
public /* readonly */ PropertyId $statementPropertyId;
private ?PropertyId $qualifierPropertyId;
/**
* @param string $template $ is replaced by the value
*/
public function __construct( string $template, PropertyId $statementProperty, ?PropertyId $qualifierProperty ) {
$this->template = $template;
$this->statementPropertyId = $statementProperty;
$this->qualifierPropertyId = $qualifierProperty;
}
public function buildString( StatementList $statements ): ?string {
foreach ( $this->getValuesForSegment( $statements ) as $dataValue ) {
if ( $dataValue instanceof StringValue ) {
return $this->replaceDollar( $dataValue->getValue() );
}
}
return null;
}
private function replaceDollar( string $parameter ): string {
return str_replace( '$', $parameter, $this->template );
}
/**
* @return DataValue[]
*/
private function getValuesForSegment( StatementList $statements ): array {
$values = [];
foreach ( $statements->getByPropertyId( $this->statementPropertyId )->getBestStatements()->toArray() as $statement ) {
$values[] = $this->getValueFromSegment( $statement );
}
return array_filter( $values, fn ( $v ) => $v !== null );
}
private function getValueFromSegment( Statement $statement ): ?DataValue {
if ( $this->qualifierPropertyId === null ) {
return $this->getMainSnakValue( $statement );
}
return $this->getQualifierValue( $statement );
}
private function getMainSnakValue( Statement $statement ): ?DataValue {
$mainSnak = $statement->getMainSnak();
if ( $mainSnak instanceof PropertyValueSnak ) {
return $mainSnak->getDataValue();
}
return null;
}
private function getQualifierValue( Statement $statement ): ?DataValue {
/**
* @var Snak $qualifier
*/
foreach ( $statement->getQualifiers() as $qualifier ) {
if ( $qualifier instanceof PropertyValueSnak ) {
if ( $qualifier->getPropertyId()->equals( $this->qualifierPropertyId ) ) {
return $qualifier->getDataValue();
}
}
}
return null;
}
}