1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Wikibase\Api\Service; |
4
|
|
|
|
5
|
|
|
use Deserializers\Deserializer; |
6
|
|
|
use Mediawiki\Api\MediawikiApi; |
7
|
|
|
use Mediawiki\Api\SimpleRequest; |
8
|
|
|
use RuntimeException; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* @access private |
12
|
|
|
* |
13
|
|
|
* @author Addshore |
14
|
|
|
* @author Thomas Arrow |
15
|
|
|
*/ |
16
|
|
|
class ValueParser { |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var MediawikiApi |
20
|
|
|
*/ |
21
|
|
|
private $api; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @var Deserializer |
25
|
|
|
*/ |
26
|
|
|
private $dataValueDeserializer; |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param MediawikiApi $api |
30
|
|
|
* @param Deserializer $dataValueDeserializer |
31
|
|
|
*/ |
32
|
|
|
public function __construct( MediawikiApi $api, Deserializer $dataValueDeserializer ) { |
33
|
|
|
$this->api = $api; |
34
|
|
|
$this->dataValueDeserializer = $dataValueDeserializer; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @since 0.2 |
39
|
|
|
* |
40
|
|
|
* @param string|string[] $inputValues one or more |
41
|
|
|
* @param string $parser Id of the ValueParser to use |
42
|
|
|
* |
43
|
|
|
* @return DataValue|DataValue[] if array parsed object has same array key as value |
44
|
|
|
*/ |
45
|
|
|
public function parse( $inputValues, $parser ) { |
46
|
|
|
return $this->parseAsync( $inputValues, $parser )->wait(); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @since 0.7 |
51
|
|
|
* |
52
|
|
|
* @param string|string[] $inputValues one or more |
53
|
|
|
* @param string $parser Id of the ValueParser to use |
54
|
|
|
* |
55
|
|
|
* @return Promise of a DataValue object or array of DataValue objects with same keys as values |
56
|
|
|
*/ |
57
|
|
|
public function parseAsync( $inputValues, $parser ) { |
58
|
|
|
$promise = $this->api->getRequestAsync( |
59
|
|
|
new SimpleRequest( |
60
|
|
|
'wbparsevalue', |
61
|
|
|
[ |
62
|
|
|
'parser' => $parser, |
63
|
|
|
'values' => implode( '|', $inputValues ), |
64
|
|
|
] |
65
|
|
|
) |
66
|
|
|
); |
67
|
|
|
|
68
|
|
|
return $promise->then( |
69
|
|
|
function ( $result ) use ( $inputValues ) { |
70
|
|
|
if ( is_array( $inputValues ) ) { |
71
|
|
|
$indexedResults = []; |
72
|
|
|
foreach ( $result['results'] as $resultElement ) { |
73
|
|
|
if ( in_array( $resultElement['raw'], $inputValues ) ) { |
74
|
|
|
$indexedResults[array_search( $resultElement['raw'], $inputValues )] = |
75
|
|
|
$this->dataValueDeserializer->deserialize( $resultElement ); |
76
|
|
|
} else { |
77
|
|
|
throw new RuntimeException( "Failed to match parse results with input data" ); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
return $indexedResults; |
82
|
|
|
} else { |
83
|
|
|
return $this->dataValueDeserializer->deserialize( $result['results'][0] ); |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
); |
87
|
|
|
} |
88
|
|
|
|
89
|
|
|
} |
90
|
|
|
|