Query::getXml()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 3
eloc 14
c 2
b 0
f 0
nc 3
nop 1
dl 0
loc 19
ccs 0
cts 18
cp 0
crap 12
rs 9.7998
1
<?php
2
3
namespace Samwilson\SimpleWikidata;
4
5
use Exception;
6
use GuzzleHttp\Client;
7
use Psr\Cache\CacheItemPoolInterface;
8
use SimpleXmlElement;
9
10
class Query {
11
12
	/** @var string */
13
	protected $query;
14
15
	/** @var string */
16
	protected $lang;
17
18
	/** @var CacheItemPoolInterface */
19
	protected $cache;
20
21
	/**
22
	 * Query constructor.
23
	 * @param string $query The Sparql query.
24
	 * @param string $lang The language.
25
	 * @param CacheItemPoolInterface $cache The cache.
26
	 */
27
	public function __construct( $query, $lang, CacheItemPoolInterface $cache ) {
28
		$this->query = $query;
29
		$this->lang = $lang;
30
		$this->cache = $cache;
31
	}
32
33
	/**
34
	 * Get the items.
35
	 * @return Item[] The results.
36
	 */
37
	public function getItems() {
38
		$xml = $this->getXml( $this->query );
39
		$results = [];
40
		foreach ( $xml->results->result as $res ) {
41
			$result = $this->getBindings( $res );
42
			$id = substr( $result['item'], strrpos( $result['item'], '/' ) + 1 );
43
			$item = Item::factory( $id, $this->lang, $this->cache );
44
			$results[] = $item;
45
		}
46
		return $results;
47
	}
48
49
	/**
50
	 * @param string $query The Sparql query.
51
	 * @return SimpleXmlElement
52
	 * @throws Exception
53
	 */
54
	protected function getXml( $query ) {
55
		$url = "https://query.wikidata.org/bigdata/namespace/wdq/sparql";
56
		$client = new Client();
57
		try {
58
			$response = $client->request( 'GET', $url, [
59
				// https://meta.wikimedia.org/wiki/User-Agent_policy
60
				'User-Agent' => 'samwilson/simple-wikidata (User:Samwilson) PHP',
61
				'query' => [ 'query' => $query ],
62
			] );
63
		} catch ( Exception $e ) {
64
			throw new Exception( "Unable to run query: <pre>" . htmlspecialchars( $query ) . "</pre>", 500 );
65
		}
66
		$result = $response->getBody()->getContents();
67
		if ( empty( $result ) ) {
68
			$msg = "No result from query: <pre>" . htmlspecialchars( $query ) . "</pre>";
69
			throw new Exception( $msg, 500 );
70
		}
71
		$xml = new SimpleXmlElement( $result );
72
		return $xml;
73
	}
74
75
	/**
76
	 * @param SimpleXmlElement $xml The query result XML.
77
	 * @return array
78
	 */
79
	protected function getBindings( $xml ) {
80
		$out = [];
81
		foreach ( $xml->binding as $binding ) {
82
			if ( isset( $binding->literal ) ) {
83
				$out[(string)$binding['name']] = (string)$binding->literal;
84
			}
85
			if ( isset( $binding->uri ) ) {
86
				$out[(string)$binding['name']] = (string)$binding->uri;
87
			}
88
		}
89
		return $out;
90
	}
91
92
}
93