Completed
Push — master ( 0406c2...d58e57 )
by Christian
04:47
created

PiwikConnection::send()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
rs 9.4286
cc 2
eloc 7
nc 2
nop 1
1
<?php
2
3
/*
4
 * This file is part of the ni-ju-san CMS.
5
 *
6
 * (c) Christian Gripp <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Core23\PiwikBundle\Connection;
13
14
use Core23\PiwikBundle\Exception\PiwikException;
15
use GuzzleHttp\Client;
16
17
class PiwikConnection implements ConnectionInterface
18
{
19
    /**
20
     * @var Client
21
     */
22
    private $client;
23
24
    /**
25
     * @var string
26
     */
27
    private $apiUrl;
28
29
    /**
30
     * Initialize client.
31
     *
32
     * @param string $apiUrl base API URL
33
     * @param Client $client guzzle client
34
     */
35
    public function __construct($apiUrl, Client $client = null)
36
    {
37
        if (null === $client) {
38
            $this->client = new Client(array('base_uri' => $apiUrl));
39
        } else {
40
            $this->client = $client;
41
        }
42
        $this->apiUrl = $apiUrl;
43
    }
44
45
    /**
46
     * {@inheritdoc}
47
     */
48
    public function send(array $params = array())
49
    {
50
        $params['module'] = 'API';
51
        $url              = $this->apiUrl.'?'.$this->getUrlParamString($params);
52
53
        $response = $this->client->get($url);
54
55
        if (!$response->getStatusCode() === 200) {
56
            throw new PiwikException(sprintf('"%s" returned an invalid status code: "%s"', $url, $response->getStatusCode()));
57
        }
58
59
        return $response->getBody();
60
    }
61
62
    /**
63
     * Converts a set of parameters to a query string.
64
     *
65
     * @param array $params
66
     *
67
     * @return string query string
68
     */
69
    protected function getUrlParamString(array $params)
70
    {
71
        $query = array();
72
        foreach ($params as $key => $val) {
73
            if (is_array($val)) {
74
                $val = implode(',', $val);
75
            } elseif ($val instanceof \DateTime) {
76
                $val = $val->format('Y-m-d');
77
            } elseif (is_bool($val)) {
78
                if ($val) {
79
                    $val = 1;
80
                } else {
81
                    continue;
82
                }
83
            } else {
84
                $val = urlencode($val);
85
            }
86
            $query[] = $key.'='.$val;
87
        }
88
89
        return implode('&', $query);
90
    }
91
}
92