ValueParser   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 74
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 6
lcom 1
cbo 4
dl 0
loc 74
rs 10
c 0
b 0
f 0
ccs 0
cts 28
cp 0

3 Methods

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