1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Chuckbe\Chuckcms\Chuck\Matomo; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Default implementation of a query for the Matomo reporting API. |
7
|
|
|
*/ |
8
|
|
|
class Query implements QueryInterface |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* An HTTP client that encapsulates a GuzzleHttp client. |
12
|
|
|
* |
13
|
|
|
* @var \Chuckbe\Chuckcms\Chuck\Matomo\HttpClient |
14
|
|
|
*/ |
15
|
|
|
protected $httpClient; |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Associative array of query parameters, keyed by parameter name. |
19
|
|
|
* |
20
|
|
|
* @var array |
21
|
|
|
*/ |
22
|
|
|
protected $parameters; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Constructs a new Query object. |
26
|
|
|
* |
27
|
|
|
* @param string $url |
28
|
|
|
* The URL of the Matomo server. |
29
|
|
|
* @param \Chuckbe\Chuckcms\Chuck\Matomo\HttpClient $httpClient |
30
|
|
|
* The HTTP client wrapper. |
31
|
|
|
*/ |
32
|
|
|
public function __construct($url, HttpClient $httpClient) |
33
|
|
|
{ |
34
|
|
|
$this->httpClient = $httpClient; |
35
|
|
|
$this->httpClient->setUrl($url); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* {@inheritdoc} |
40
|
|
|
*/ |
41
|
|
|
public function setParameters(array $parameters) |
42
|
|
|
{ |
43
|
|
|
foreach ($parameters as $name => $value) { |
44
|
|
|
$this->setParameter($name, $value); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
return $this; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* {@inheritdoc} |
52
|
|
|
*/ |
53
|
|
|
public function setParameter($name, $value) |
54
|
|
|
{ |
55
|
|
|
$this->parameters[$name] = $value; |
56
|
|
|
|
57
|
|
|
return $this; |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* {@inheritdoc} |
62
|
|
|
*/ |
63
|
|
|
public function getParameters() |
64
|
|
|
{ |
65
|
|
|
return $this->parameters; |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* {@inheritdoc} |
70
|
|
|
*/ |
71
|
|
|
public function getParameter($name) |
72
|
|
|
{ |
73
|
|
|
if (!array_key_exists($name, $this->parameters)) { |
74
|
|
|
throw new \InvalidArgumentException("Parameter '$name' is not set."); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
return $this->parameters[$name]; |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* Prepares the query for execution. |
82
|
|
|
*/ |
83
|
|
|
protected function prepareExecute() |
84
|
|
|
{ |
85
|
|
|
// Set the format to JSON. |
86
|
|
|
$this->setParameter('format', 'json'); |
87
|
|
|
|
88
|
|
|
// Use the reporting API. |
89
|
|
|
$this->setParameter('module', 'API'); |
90
|
|
|
} |
91
|
|
|
|
92
|
|
|
/** |
93
|
|
|
* {@inheritdoc} |
94
|
|
|
*/ |
95
|
|
|
public function execute() |
96
|
|
|
{ |
97
|
|
|
$this->prepareExecute(); |
98
|
|
|
$response = $this->httpClient->setRequestParameters($this->parameters)->sendRequest(); |
99
|
|
|
|
100
|
|
|
return new QueryResult($response); |
101
|
|
|
} |
102
|
|
|
} |
103
|
|
|
|