Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
0.00% |
0 / 29 |
|
0.00% |
0 / 4 |
CRAP | |
0.00% |
0 / 1 |
WikidataDriver | |
0.00% |
0 / 29 |
|
0.00% |
0 / 4 |
156 | |
0.00% |
0 / 1 |
getBackendUrl | |
0.00% |
0 / 2 |
|
0.00% |
0 / 1 |
2 | |||
search | |
0.00% |
0 / 17 |
|
0.00% |
0 / 1 |
20 | |||
element2String | |
0.00% |
0 / 3 |
|
0.00% |
0 / 1 |
12 | |||
getResults | |
0.00% |
0 / 7 |
|
0.00% |
0 / 1 |
20 |
1 | <?php |
2 | |
3 | use MediaWiki\MediaWikiServices; |
4 | |
5 | class WikidataDriver { |
6 | |
7 | /** @var string */ |
8 | private $lang = 'en'; |
9 | /** @var bool|array */ |
10 | private $data = false; |
11 | |
12 | /** |
13 | * @return string |
14 | */ |
15 | public function getBackendUrl() { |
16 | $config = MediaWikiServices::getInstance()->getConfigFactory()->makeConfig( 'main' ); |
17 | return $config->get( "MathSearchWikidataUrl" ); |
18 | } |
19 | |
20 | public function search( $term ) { |
21 | $term = urlencode( $term ); |
22 | $request = [ |
23 | 'method' => 'GET', |
24 | 'url' => $this->getBackendUrl() . |
25 | "/w/api.php?format=json&action=wbsearchentities&uselang={$this->lang}" . |
26 | "&language={$this->lang}&search={$term}" |
27 | ]; |
28 | |
29 | $multiHttpClient = MediaWikiServices::getInstance()->getHttpRequestFactory() |
30 | ->createMultiClient(); |
31 | $response = $multiHttpClient->run( $request ); |
32 | if ( $response['code'] === 200 ) { |
33 | $json = json_decode( $response['body'] ); |
34 | if ( $json && json_last_error() === JSON_ERROR_NONE ) { |
35 | $this->data = $json; |
36 | return true; |
37 | } |
38 | } |
39 | $this->data = false; |
40 | return false; |
41 | } |
42 | |
43 | private function element2String( $d, $desc = true ) { |
44 | if ( $desc && isset( $d->description ) ) { |
45 | return "{$d->label} ({$d->description})"; |
46 | } else { |
47 | return $d->label; |
48 | } |
49 | } |
50 | |
51 | public function getResults( $links = false, $desc = true ) { |
52 | $res = []; |
53 | if ( $this->data ) { |
54 | foreach ( $this->data->search as $d ) { |
55 | if ( $links ) { |
56 | $res[$d->id] = "<a href='{$d->concepturi}'>{$this->element2String($d, $desc)}</a>"; |
57 | } else { |
58 | $res[$d->id] = $this->element2String( $d, $desc ); |
59 | } |
60 | } |
61 | } |
62 | return $res; |
63 | } |
64 | } |