Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
Total | |
0.00% |
0 / 25 |
|
0.00% |
0 / 3 |
CRAP | |
0.00% |
0 / 1 |
WikidataIdFetcher | |
0.00% |
0 / 25 |
|
0.00% |
0 / 3 |
72 | |
0.00% |
0 / 1 |
__construct | |
0.00% |
0 / 1 |
|
0.00% |
0 / 1 |
2 | |||
getQuery | |
0.00% |
0 / 7 |
|
0.00% |
0 / 1 |
2 | |||
getWikidataId | |
0.00% |
0 / 17 |
|
0.00% |
0 / 1 |
42 |
1 | <?php |
2 | declare( strict_types = 1 ); |
3 | |
4 | namespace ContentTranslation\Service; |
5 | |
6 | use ContentTranslation\SiteMapper; |
7 | use MediaWiki\Http\HttpRequestFactory; |
8 | use MediaWiki\Json\FormatJson; |
9 | |
10 | class WikidataIdFetcher { |
11 | private HttpRequestFactory $httpRequestFactory; |
12 | |
13 | public function __construct( HttpRequestFactory $httpRequestFactory ) { |
14 | $this->httpRequestFactory = $httpRequestFactory; |
15 | } |
16 | |
17 | /** |
18 | * @param string $title |
19 | * @return array |
20 | */ |
21 | protected function getQuery( string $title ): array { |
22 | return [ |
23 | 'action' => 'query', |
24 | 'format' => 'json', |
25 | 'formatversion' => 2, |
26 | 'prop' => 'pageprops', |
27 | 'titles' => $title |
28 | ]; |
29 | } |
30 | |
31 | public function getWikidataId( string $title, string $language ): ?string { |
32 | $query = $this->getQuery( $title ); |
33 | |
34 | $page = null; |
35 | |
36 | $baseUrl = SiteMapper::getApiURL( $language ); |
37 | $url = wfAppendQuery( $baseUrl, $query ); |
38 | |
39 | try { |
40 | $response = $this->httpRequestFactory->get( $url, [], __METHOD__ ); |
41 | } catch ( \Exception $exception ) { |
42 | return null; |
43 | } |
44 | |
45 | if ( $response === null ) { |
46 | return null; |
47 | } |
48 | |
49 | $response = FormatJson::decode( $response, true ); |
50 | |
51 | if ( isset( $response['query']['pages'] ) ) { |
52 | $pages = array_values( $response['query']['pages'] ); |
53 | if ( count( $pages ) === 1 ) { |
54 | $page = $pages[0]; |
55 | } |
56 | } |
57 | |
58 | if ( isset( $page['missing'] ) ) { |
59 | // Page does not exist. Nothing to do. |
60 | return null; |
61 | } |
62 | |
63 | return $page['pageprops']['wikibase_item'] ?? null; |
64 | } |
65 | } |