OpenExchangeRatesDriver::setAppId()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
/*
4
 * This file is part of the ONGR package.
5
 *
6
 * (c) NFQ Technologies UAB <[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 ONGR\CurrencyExchangeBundle\Driver;
13
14
use GuzzleHttp\Client;
15
16
/**
17
 * This class downloads exchange rates from openexchangerates.org.
18
 */
19
class OpenExchangeRatesDriver implements CurrencyDriverInterface
20
{
21
    /**
22
     * @var string
23
     */
24
    private $appId;
25
26
    /**
27
     * @var string
28
     */
29
    private $url;
30
31
    /**
32
     * @var null|Client
33
     */
34
    private $httpClient;
35
36
    /**
37
     * @return string
38
     */
39
    public function getAppId()
40
    {
41
        return $this->appId;
42
    }
43
44
    /**
45
     * @param string $appId
46
     */
47
    public function setAppId($appId)
48
    {
49
        $this->appId = $appId;
50
    }
51
52
    /**
53
     * @param null|Client $httpClient
54
     * @param string $url
55
     */
56
    public function __construct(Client $httpClient, $url)
57
    {
58
        $this->httpClient = $httpClient;
59
        $this->url = $url;
60
    }
61
62
    /**
63
     * Downloads raw currency data.
64
     *
65
     * @return array
66
     */
67
    private function getRawData()
68
    {
69
        $request = $this->httpClient->get(
70
            $this->url,
71
            ['query' => ['app_id' => $this->getAppId()]]
72
        );
73
74
        return json_decode($request->getBody(), true);
75
    }
76
77
    /**
78
     * {@inheritdoc}
79
     */
80
    public function getRates($date = null)
81
    {
82
        $response = $this->getRawData();
83
84
        // Validate response.
85
        $valid = isset($response) && is_array($response) && isset($response['base']) && isset($response['rates']);
86
        if (!$valid) {
87
            throw new \UnexpectedValueException('Got invalid response');
88
        }
89
90
        // Check if base currency is correct.
91
        if ($response['base'] != $this->getBaseCurrency()) {
92
            throw new \UnexpectedValueException(
93
                sprintf(
94
                    'We expected to get values in base currency USD. Got %s',
95
                    $response['base']
96
                )
97
            );
98
        }
99
100
        return $response['rates'];
101
    }
102
103
    /**
104
     * {@inheritdoc}
105
     */
106
    public function getBaseCurrency()
107
    {
108
        return 'USD';
109
    }
110
}
111