WDQSResource::resolve()   A
last analyzed

Complexity

Conditions 2
Paths 8

Size

Total Lines 41
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 23
c 1
b 0
f 0
dl 0
loc 41
rs 9.552
cc 2
nc 8
nop 1
1
<?php
2
3
class WDQSResource extends RemoteResource
4
{
5
    public const WDQS_ENDPOINT = "https://query.wikidata.org/sparql";
6
7
    public function resolve(int $timeout): ?EasyRdf\Resource
8
    {
9
        try {
10
            // change the timeout setting for external requests
11
            $httpclient = EasyRdf\Http::getDefaultHttpClient();
12
            $httpclient->setConfig(array('timeout' => $timeout, 'useragent' => 'Skosmos'));
13
            $httpclient->setHeaders('Accept', 'text/turtle');
14
            EasyRdf\Http::setDefaultHttpClient($httpclient);
15
16
            $uri = $this->uri;
17
            $query = <<<EOQ
18
PREFIX wd:     <http://www.wikidata.org/entity/>
19
PREFIX rdfs:   <http://www.w3.org/2000/01/rdf-schema#>
20
PREFIX schema: <http://schema.org/>
21
22
CONSTRUCT {
23
  <$uri> rdfs:label ?label .
24
  ?link schema:about <$uri> ;
25
    a ?linktype ;
26
    schema:isPartOf ?whole ;
27
    schema:inLanguage ?lang .
28
}
29
WHERE
30
{
31
  { <$uri> rdfs:label ?label }
32
  UNION
33
  {
34
    ?link schema:about <$uri> ;
35
      a ?linktype ;
36
      schema:isPartOf ?whole ;
37
      schema:inLanguage ?lang .
38
  }
39
}
40
EOQ;
41
42
            $client = new EasyRdf\Sparql\Client(self::WDQS_ENDPOINT);
43
            $graph = $client->query($query);
44
            return $graph->resource($this->uri);
45
        } catch (Exception $e) {
46
            $this->model->getLogger()->info("WDQS resolution failed for <{$this->uri}>: $e");
47
            return null;
48
        }
49
    }
50
}
51