QueryExecuter::execute()   A
last analyzed

Complexity

Conditions 3
Paths 4

Size

Total Lines 15
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 0
loc 15
rs 9.4285
cc 3
eloc 7
nc 4
nop 1
1
<?php
2
3
namespace Asparagus;
4
5
use InvalidArgumentException;
6
use RangeException;
7
use RuntimeException;
8
9
/**
10
 * Allows the execution of a query to a remote SPARQL endpoint.
11
 *
12
 * @since 0.1
13
 *
14
 * @license GNU GPL v2+
15
 * @author Bene* < [email protected] >
16
 */
17
class QueryExecuter {
18
19
	/**
20
	 * @var string
21
	 */
22
	private $url;
23
24
	/**
25
	 * @var string[]
26
	 */
27
	private $options;
28
29
	/**
30
	 * @var Http
31
	 */
32
	private $http;
33
34
	/**
35
	 * @param string $url
36
	 * @param string[] $options one of queryParam, formatParam or userAgent
37
	 * @param Http|null $http
38
	 */
39
	public function __construct( $url, array $options = array(), Http $http = null ) {
40
		$this->url = $url;
41
		$this->options = array_merge( array(
0 ignored issues
show
Documentation Bug introduced by
It seems like array_merge(array('query...aragus 0.1'), $options) of type array<string|integer,str...,"userAgent":"string"}> is incompatible with the declared type array<integer,string> of property $options.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
42
			'queryParam' => 'query',
43
			'formatParam' => 'format',
44
			'userAgent' => 'Asparagus/Asparagus 0.1'
45
		), $options );
46
		$this->http = $http ?: new Http( $this->options['userAgent'] );
47
	}
48
49
	/**
50
	 * Executes the given SPARQL query.
51
	 *
52
	 * @param string|QueryBuilder $query
53
	 * @return array
54
	 * @throws InvalidArgumentException
55
	 * @throws RangeException
56
	 * @throws RuntimeException
57
	 */
58
	public function execute( $query ) {
59
		if ( $query instanceof QueryBuilder ) {
60
			$query = $query->getSPARQL();
61
		}
62
63
		if ( !is_string( $query ) ) {
64
			throw new InvalidArgumentException( '$query has to be a string or an instance of QueryBuilder' );
65
		}
66
67
		$result = $this->getResult( $query );
68
		
69
		// TODO also support ask queries (with key 'boolean')
70
		//      https://www.w3.org/TR/rdf-sparql-json-res/
71
		return $result['results'];
72
	}
73
74
	private function getResult( $query ) {
75
		$result = $this->http->request( $this->url, array(
76
			$this->options['queryParam'] => $query,
77
			$this->options['formatParam'] => 'json'
78
		) );
79
80
		return json_decode( $result, true );
81
	}
82
83
}
84