PiwikConnection::send()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 8
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
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 Http\Client\HttpClient;
16
use Http\Message\MessageFactory;
17
18
final class PiwikConnection implements ConnectionInterface
19
{
20
    /**
21
     * @var HttpClient
22
     */
23
    private $client;
24
25
    /**
26
     * @var MessageFactory
27
     */
28
    private $messageFactory;
29
30
    /**
31
     * @var string
32
     */
33
    private $apiUrl;
34
35
    /**
36
     * Initialize client.
37
     *
38
     * @param HttpClient     $client
39
     * @param MessageFactory $messageFactory
40
     * @param string         $apiUrl         base API URL
41
     */
42
    public function __construct(HttpClient $client, MessageFactory $messageFactory, string $apiUrl)
43
    {
44
        $this->apiUrl         = $apiUrl;
45
        $this->client         = $client;
46
        $this->messageFactory = $messageFactory;
47
    }
48
49
    /**
50
     * {@inheritdoc}
51
     */
52
    public function send(array $params = []): string
53
    {
54
        $params['module'] = 'API';
55
56
        $url      = $this->apiUrl.'?'.$this->getUrlParamString($params);
57
        $request  = $this->messageFactory->createRequest('GET', $url);
58
        $response = $this->client->sendRequest($request);
59
60
        if (200 !== $response->getStatusCode()) {
61
            throw new PiwikException(sprintf('"%s" returned an invalid status code: "%s"', $url, $response->getStatusCode()));
62
        }
63
64
        return $response->getBody()->getContents();
65
    }
66
67
    /**
68
     * Converts a set of parameters to a query string.
69
     *
70
     * @param array $params
71
     *
72
     * @return string query string
73
     */
74
    private function getUrlParamString(array $params): string
75
    {
76
        $query = [];
77
        foreach ($params as $key => $val) {
78
            if (is_array($val)) {
79
                $val = implode(',', $val);
80
            } elseif ($val instanceof \DateTime) {
81
                $val = $val->format('Y-m-d');
82
            } elseif (is_bool($val)) {
83
                if ($val) {
84
                    $val = 1;
85
                } else {
86
                    continue;
87
                }
88
            } else {
89
                $val = urlencode((string) $val);
90
            }
91
            $query[] = $key.'='.$val;
92
        }
93
94
        return implode('&', $query);
95
    }
96
}
97