Completed
Pull Request — master (#49)
by
unknown
02:01
created

EcbDriver::getBaseCurrency()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 2
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 5
rs 9.4285
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
     * @var string
28
     */
29
    private $url;
30
31
    /**
32
     * @param null|Client $httpClient
33
     * @param string      $url
34
     */
35
    public function __construct(Client $httpClient, $url)
36
    {
37
        $this->httpClient = $httpClient;
38
        $this->url = $url;
39
    }
40
41
    /**
42
     * Downloads raw currency data.
43
     *
44
     * @return array
45
     */
46
    private function getRawData()
47
    {
48
        $request = $this->httpClient->get($this->url);
49
50
        try {
51
            $xml = simplexml_load_string((string)$request->getBody(), 'SimpleXMLElement');
52
        } catch (\Exception $e) {
53
            throw new \UnexpectedValueException('Got invalid response');
54
        }
55
56
        return $xml;
57
    }
58
59
    /**
60
     * {@inheritdoc}
61
     */
62
    public function getRates()
63
    {
64
        $rates = [];
65
        $response = $this->getRawData();
66
67
        $valid = isset($response) && isset($response->Cube->Cube->Cube);
68
        if (!$valid) {
69
            throw new \UnexpectedValueException('Got invalid response');
70
        }
71
72
        $data = $response->xpath('//gesmes:Envelope/*[3]/*');
73
        foreach ($data[0]->children() as $child) {
74
            $code = (string)$child->attributes()->currency;
75
            $rate = (float)$child->attributes()->rate;
76
            $rates[$code] = $rate;
77
        }
78
79
        return $rates;
80
    }
81
82
    /**
83
     * {@inheritdoc}
84
     */
85
    public function getBaseCurrency()
86
    {
87
        // Default base currency of The European Central Bank
88
        return 'EUR';
89
    }
90
}
91