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 http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml. |
18
|
|
|
*/ |
19
|
|
|
class EcbDriver implements CurrencyDriverInterface |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* @var null|Client |
23
|
|
|
*/ |
24
|
|
|
private $httpClient; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @param null|Client $httpClient |
28
|
|
|
*/ |
29
|
|
|
public function __construct(Client $httpClient = null) |
30
|
|
|
{ |
31
|
|
|
$this->httpClient = $httpClient ? $httpClient : new Client(); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Downloads raw currency data. |
36
|
|
|
* |
37
|
|
|
* @return array |
38
|
|
|
*/ |
39
|
|
|
private function getRawData() |
40
|
|
|
{ |
41
|
|
|
$request = $this->httpClient->get( |
42
|
|
|
'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml' |
43
|
|
|
); |
44
|
|
|
|
45
|
|
|
try { |
46
|
|
|
$xml = simplexml_load_string((string)$request->getBody(), 'SimpleXMLElement'); |
47
|
|
|
} catch (\Exception $e) { |
48
|
|
|
throw new \UnexpectedValueException('Got invalid response'); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
return $xml; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* {@inheritdoc} |
56
|
|
|
*/ |
57
|
|
|
public function getRates() |
58
|
|
|
{ |
59
|
|
|
$rates = []; |
60
|
|
|
$response = $this->getRawData(); |
61
|
|
|
|
62
|
|
|
$valid = isset($response) && isset($response->Cube->Cube->Cube); |
63
|
|
|
if (!$valid) { |
64
|
|
|
throw new \UnexpectedValueException('Got invalid response'); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
$data = $response->xpath('//gesmes:Envelope/*[3]/*'); |
68
|
|
|
foreach ($data[0]->children() as $child) { |
69
|
|
|
$code = (string)$child->attributes()->currency; |
70
|
|
|
$rate = (float)$child->attributes()->rate; |
71
|
|
|
$rates[$code] = $rate; |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return $rates; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
/** |
78
|
|
|
* {@inheritdoc} |
79
|
|
|
*/ |
80
|
|
|
public function getBaseCurrency() |
81
|
|
|
{ |
82
|
|
|
// Default base currency of The European Central Bank |
83
|
|
|
return 'EUR'; |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|