1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* @category Brownie/ExchangeRate |
4
|
|
|
* @author Brownie <[email protected]> |
5
|
|
|
* @license https://opensource.org/licenses/MIT |
6
|
|
|
*/ |
7
|
|
|
|
8
|
|
|
namespace Brownie\ExchangeRate\Currency; |
9
|
|
|
|
10
|
|
|
use Brownie\ExchangeRate\CurrencyInterface; |
11
|
|
|
use Brownie\ExchangeRate\Exception\InvalidExchangeRateException; |
12
|
|
|
use Brownie\ExchangeRate\Model\Currency; |
13
|
|
|
use Brownie\ExchangeRate\Service; |
14
|
|
|
use Brownie\HttpClient\Request; |
15
|
|
|
use Brownie\HttpClient\Exception\ClientException; |
16
|
|
|
use Brownie\HttpClient\Exception\ValidateException; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* Gets a list of existing currencies. |
20
|
|
|
*/ |
21
|
|
|
class CurrencyIsoOrg extends Service implements CurrencyInterface |
22
|
|
|
{ |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* The endpoint access to the list of currencies. |
26
|
|
|
* |
27
|
|
|
* @var string |
28
|
|
|
*/ |
29
|
|
|
private $endpoint = 'https://www.currency-iso.org/dam/downloads/lists/list_one.xml'; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* Returns an array of currencies. |
33
|
|
|
* |
34
|
|
|
* @return Currency[] |
35
|
|
|
* |
36
|
|
|
* @throws ClientException |
37
|
|
|
* @throws ValidateException |
38
|
|
|
* @throws InvalidExchangeRateException |
39
|
|
|
*/ |
40
|
3 |
|
public function getCurrencies() |
41
|
|
|
{ |
42
|
|
|
$response = $this |
43
|
3 |
|
->getHttpClient() |
44
|
3 |
|
->request( |
45
|
|
|
$this |
46
|
3 |
|
->getHttpClient() |
47
|
3 |
|
->createRequest() |
48
|
3 |
|
->setMethod(Request::HTTP_METHOD_GET) |
49
|
3 |
|
->setUrl($this->endpoint) |
50
|
|
|
); |
51
|
|
|
|
52
|
3 |
|
if ((200 != $response->getHttpCode()) || (empty($response->getBody()))) { |
53
|
1 |
|
throw new InvalidExchangeRateException('Invalid response from currency exchange server.'); |
54
|
|
|
} |
55
|
|
|
|
56
|
2 |
|
return $this->buildCurrencies($response->getBody()); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* Collects currency collection from server response. |
61
|
|
|
* |
62
|
|
|
* @param string $body Response body content. |
63
|
|
|
* |
64
|
|
|
* @return Currency[] |
65
|
|
|
* |
66
|
|
|
* @throws InvalidExchangeRateException |
67
|
|
|
*/ |
68
|
2 |
|
private function buildCurrencies($body) |
69
|
|
|
{ |
70
|
2 |
|
libxml_use_internal_errors(true); |
71
|
2 |
|
$xml = simplexml_load_string($body); |
72
|
|
|
|
73
|
2 |
|
if (false === $xml) { |
74
|
1 |
|
throw new InvalidExchangeRateException('Error parsing the response from the currency exchange server.'); |
75
|
|
|
} |
76
|
|
|
|
77
|
1 |
|
$currencies = []; |
78
|
1 |
|
foreach ($xml->CcyTbl->CcyNtry as $e) { |
79
|
1 |
|
$code = (string)$e->Ccy; |
80
|
1 |
|
if (!isset($currencies[$code])) { |
81
|
1 |
|
$currencies[$code] = new Currency((string)$e->CcyNm, $code, (int)$e->CcyNbr); |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|
85
|
1 |
|
return $currencies; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
|