Completed
Push — master ( 45f7ef...cf154d )
by Simonas
21:47 queued 06:48
created

OpenExchangeRatesDriver::setAppId()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
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 null|Client
28
     */
29
    private $httpClient;
30
31
    /**
32
     * @return string
33
     */
34
    public function getAppId()
35
    {
36
        return $this->appId;
37
    }
38
39
    /**
40
     * @param string $appId
41
     */
42
    public function setAppId($appId)
43
    {
44
        $this->appId = $appId;
45
    }
46
47
    /**
48
     * @param null|Client $httpClient
49
     */
50
    public function __construct(Client $httpClient = null)
51
    {
52
        $this->httpClient = $httpClient ? $httpClient : new Client();
53
    }
54
55
    /**
56
     * Downloads raw currency data.
57
     *
58
     * @return array
59
     */
60
    private function getRawData()
61
    {
62
        $request = $this->httpClient->get(
63
            'http://openexchangerates.org/api/latest.json',
64
            ['query' => ['app_id' => $this->getAppId()]]
65
        );
66
67
        return $request->json();
68
    }
69
70
    /**
71
     * {@inheritdoc}
72
     */
73
    public function getRates()
74
    {
75
        $response = $this->getRawData();
76
77
        // Validate response.
78
        $valid = isset($response) && is_array($response) && isset($response['base']) && isset($response['rates']);
79
        if (!$valid) {
80
            throw new \UnexpectedValueException('Got invalid response');
81
        }
82
83
        // Check if base currency is correct.
84
        if ($response['base'] != $this->getBaseCurrency()) {
85
            throw new \UnexpectedValueException(
86
                sprintf(
87
                    'We expected to get values in base currency USD. Got %s',
88
                    $response['base']
89
                )
90
            );
91
        }
92
93
        return $response['rates'];
94
    }
95
96
    /**
97
     * {@inheritdoc}
98
     */
99
    public function getBaseCurrency()
100
    {
101
        return 'USD';
102
    }
103
}
104