Passed
Pull Request — master (#9)
by
unknown
17:20
created

Query::getParameter()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 6
rs 10
c 0
b 0
f 0
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
    /**
12
     * An HTTP client that encapsulates a GuzzleHttp client.
13
     *
14
     * @var \Chuckbe\Chuckcms\Chuck\Matomo\HttpClient
15
     */
16
    protected $httpClient;
17
18
    /**
19
     * Associative array of query parameters, keyed by parameter name.
20
     *
21
     * @var array
22
     */
23
    protected $parameters;
24
25
    /**
26
     * Constructs a new Query object.
27
     *
28
     * @param string $url
29
     *   The URL of the Matomo server.
30
     * @param \Chuckbe\Chuckcms\Chuck\Matomo\HttpClient $httpClient
31
     *   The HTTP client wrapper.
32
     */
33
    public function __construct($url, HttpClient $httpClient)
34
    {
35
        $this->httpClient = $httpClient;
36
        $this->httpClient->setUrl($url);
37
    }
38
39
    /**
40
     * {@inheritdoc}
41
     */
42
    public function setParameters(array $parameters)
43
    {
44
        foreach ($parameters as $name => $value) {
45
            $this->setParameter($name, $value);
46
        }
47
48
        return $this;
49
    }
50
51
    /**
52
     * {@inheritdoc}
53
     */
54
    public function setParameter($name, $value)
55
    {
56
        $this->parameters[$name] = $value;
57
58
        return $this;
59
    }
60
61
    /**
62
     * {@inheritdoc}
63
     */
64
    public function getParameters()
65
    {
66
        return $this->parameters;
67
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72
    public function getParameter($name)
73
    {
74
        if (!array_key_exists($name, $this->parameters)) {
75
            throw new \InvalidArgumentException("Parameter '$name' is not set.");
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
        return new QueryResult($response);
100
    }
101
}
102