|
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
|
|
|
/** |
|
15
|
|
|
* This class downloads exchange rates from openexchangerates.org. |
|
16
|
|
|
*/ |
|
17
|
|
|
class OpenExchangeRatesDriver implements CurrencyDriverInterface |
|
18
|
|
|
{ |
|
19
|
|
|
/** |
|
20
|
|
|
* @var string |
|
21
|
|
|
*/ |
|
22
|
|
|
private $appId; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @var string |
|
26
|
|
|
*/ |
|
27
|
|
|
const REQUEST_URI = 'http://openexchangerates.org/api/latest.json?app_id=%s'; |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
30
|
|
|
* @return string |
|
31
|
|
|
*/ |
|
32
|
|
|
public function getAppId() |
|
33
|
|
|
{ |
|
34
|
|
|
return $this->appId; |
|
35
|
|
|
} |
|
36
|
|
|
|
|
37
|
|
|
/** |
|
38
|
|
|
* @param string $appId |
|
39
|
|
|
*/ |
|
40
|
|
|
public function setAppId($appId) |
|
41
|
|
|
{ |
|
42
|
|
|
$this->appId = $appId; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
|
|
* Downloads raw currency data. |
|
47
|
|
|
* |
|
48
|
|
|
* @return array |
|
49
|
|
|
*/ |
|
50
|
|
|
private function getRawData() |
|
51
|
|
|
{ |
|
52
|
|
|
$ch = curl_init(sprintf(self::REQUEST_URI, $this->appId)); |
|
53
|
|
|
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); |
|
54
|
|
|
if (($json = curl_exec($ch)) === false) { |
|
55
|
|
|
return []; |
|
56
|
|
|
} |
|
57
|
|
|
curl_close($ch); |
|
58
|
|
|
|
|
59
|
|
|
return json_decode($json, true); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
/** |
|
63
|
|
|
* {@inheritdoc} |
|
64
|
|
|
*/ |
|
65
|
|
|
public function getRates() |
|
66
|
|
|
{ |
|
67
|
|
|
$response = $this->getRawData(); |
|
68
|
|
|
|
|
69
|
|
|
// Validate response. |
|
70
|
|
|
$valid = isset($response) && is_array($response) && isset($response['base']) && isset($response['rates']); |
|
71
|
|
|
if (!$valid) { |
|
72
|
|
|
throw new \UnexpectedValueException('Got invalid response'); |
|
73
|
|
|
} |
|
74
|
|
|
|
|
75
|
|
|
// Check if base currency is correct. |
|
76
|
|
|
if ($response['base'] != $this->getBaseCurrency()) { |
|
77
|
|
|
throw new \UnexpectedValueException( |
|
78
|
|
|
sprintf( |
|
79
|
|
|
'We expected to get values in base currency USD. Got %s', |
|
80
|
|
|
$response['base'] |
|
81
|
|
|
) |
|
82
|
|
|
); |
|
83
|
|
|
} |
|
84
|
|
|
|
|
85
|
|
|
return $response['rates']; |
|
86
|
|
|
} |
|
87
|
|
|
|
|
88
|
|
|
/** |
|
89
|
|
|
* {@inheritdoc} |
|
90
|
|
|
*/ |
|
91
|
|
|
public function getBaseCurrency() |
|
92
|
|
|
{ |
|
93
|
|
|
return 'USD'; |
|
94
|
|
|
} |
|
95
|
|
|
} |
|
96
|
|
|
|