-
Notifications
You must be signed in to change notification settings - Fork 10
/
ExchangeRatesApi.php
76 lines (70 loc) · 1.92 KB
/
ExchangeRatesApi.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php
/**
* @link https://github.com/imanilchaudhari
* @copyright Copyright (c) 2024
* @license [MIT License](https://opensource.org/license/mit)
*/
namespace imanilchaudhari\CurrencyConverter\Provider;
use yii\httpclient\Client;
use yii\base\InvalidConfigException;
use imanilchaudhari\CurrencyConverter\Interface\RateProviderInterface;
/**
* Exchange Rates provides currency conversion, current and historical forex exchange rate
* and currency fluctuation data through REST API in json and xml formats compatible.
*
* To use ExchangeRatesApi, configure your app component as below
*
* ```php
*
* 'components' => [
* 'currencyConverter' => [
* 'class' => 'imanilchaudhari\CurrencyConverter\CurrencyConverter',
* 'provider' => [
* 'class' => 'imanilchaudhari\CurrencyConverter\Provider\ExchangeRatesApi',
* ],
* ],
* ],
* ```
*
* @see https://www.exchangerate-api.com/
*
* @author Anil Chaudhari <[email protected]>
* @since 1.0
*/
class ExchangeRatesApi implements RateProviderInterface
{
/**
* Yii http client
*
* @var Client
*/
private $_client;
/**
* Create a new provider instance.
*
* @return void
*/
public function __construct()
{
$this->_client = new Client([
'baseUrl' => 'https://open.er-api.com',
'transport' => 'yii\httpclient\CurlTransport',
]);
}
/**
* {@inheritDoc}
*/
public function getRate($source, $target)
{
try {
$response = $this->_client->get("/v6/latest/$source")->send();
$content = $response->getData();
if ($response->isOk && ($content['result'] == 'success')) {
return $content['rates'][$target];
}
throw new InvalidConfigException($content['message']);
} catch (\Exception $ex) {
throw $ex;
}
}
}