-
Notifications
You must be signed in to change notification settings - Fork 8
/
WikibaseAPIClient.php
86 lines (73 loc) · 2.55 KB
/
WikibaseAPIClient.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use Illuminate\Http\Client\Response;
use App\Exceptions\WikibaseValueParserException;
use Kevinrob\GuzzleCache\CacheMiddleware;
use App\Exceptions\WikibaseAPIClientException;
class WikibaseAPIClient
{
/**
* @var string wikibase api url
*/
private $baseUrl;
/**
* @var CacheMiddleware Guzzlehttp response caching middleware
*/
private $cache;
public function __construct(string $baseUrl, CacheMiddleware $cache)
{
$this->baseUrl = $baseUrl;
$this->cache = $cache;
}
private function get(string $action, array $params): Response
{
$response = Http::withMiddleware($this->cache)
->get($this->baseUrl, array_merge([
'action' => $action,
'format' => 'json',
'maxage' => config('wikidata.response_cache.ttl')
], $params));
// Checking for an errors field in the response, since Wikibase api
// responds with 200 even for erroneous requests
if (isset($response['error'])) {
throw new WikibaseAPIClientException($response['error']['info']);
}
return $response;
}
public function parseValue(string $property, $value): Response
{
try {
return $this->get('wbparsevalue', [
'values' => $value,
'property' => $property,
'validate' => true
]);
} catch (WikibaseAPIClientException $e) {
throw new WikibaseValueParserException($e->getMessage());
}
}
public function formatEntities(array $ids, string $lang): Response
{
$response = $this->get('wbformatentities', [
'ids' => implode('|', $ids),
'uselang' => $lang
]);
return $response;
}
public function getLabels(array $ids, string $lang): array
{
// wbformatentities only allows for up to 50 entities to be formatted at a time
return collect($ids)->chunk(50)
->map(function ($chunk) use ($lang) {
$response = $this->formatEntities($chunk->toArray(), $lang);
return $response['wbformatentities'];
})
->collapse()
// The code below was added due to the fact that wbformatentities only
// returns labels formatted as html links, however we only require the
// label text. Therefore, we extract the text from the links.
->map('strip_tags')
->toArray();
}
}