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 | |
| 12 | public function __construct( |
| 13 | private readonly HttpRequestFactory $httpRequestFactory |
| 14 | ) { |
| 15 | } |
| 16 | |
| 17 | protected function getQuery( string $title ): array { |
| 18 | return [ |
| 19 | 'action' => 'query', |
| 20 | 'format' => 'json', |
| 21 | 'formatversion' => 2, |
| 22 | 'prop' => 'pageprops', |
| 23 | 'titles' => $title |
| 24 | ]; |
| 25 | } |
| 26 | |
| 27 | public function getWikidataId( string $title, string $language ): ?string { |
| 28 | $query = $this->getQuery( $title ); |
| 29 | |
| 30 | $page = null; |
| 31 | |
| 32 | $baseUrl = SiteMapper::getApiURL( $language ); |
| 33 | $url = wfAppendQuery( $baseUrl, $query ); |
| 34 | |
| 35 | try { |
| 36 | $response = $this->httpRequestFactory->get( $url, [], __METHOD__ ); |
| 37 | } catch ( \Exception ) { |
| 38 | return null; |
| 39 | } |
| 40 | |
| 41 | if ( $response === null ) { |
| 42 | return null; |
| 43 | } |
| 44 | |
| 45 | $response = FormatJson::decode( $response, true ); |
| 46 | |
| 47 | if ( isset( $response['query']['pages'] ) ) { |
| 48 | $pages = array_values( $response['query']['pages'] ); |
| 49 | if ( count( $pages ) === 1 ) { |
| 50 | $page = $pages[0]; |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | if ( isset( $page['missing'] ) ) { |
| 55 | // Page does not exist. Nothing to do. |
| 56 | return null; |
| 57 | } |
| 58 | |
| 59 | return $page['pageprops']['wikibase_item'] ?? null; |
| 60 | } |
| 61 | } |