-
Notifications
You must be signed in to change notification settings - Fork 10
/
FixerApi.php
91 lines (82 loc) · 2.18 KB
/
FixerApi.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?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;
/**
* Fixer provides currency conversion, current and historical forex exchange rate
* and currency fluctuation data through REST API in json and xml formats compatible.
*
* To use FixerApi, configure your app component as below
*
* ```php
*
* 'components' => [
* 'currencyConverter' => [
* 'class' => 'imanilchaudhari\CurrencyConverter\CurrencyConverter',
* 'provider' => [
* 'class' => 'imanilchaudhari\CurrencyConverter\Provider\FixerApi',
* 'access_key' => 'your-access-key',
* ],
* ],
* ],
* ```
*
* @see https://fixer.io/
*
* @author Anil Chaudhari <[email protected]>
* @since 1.0
*/
class FixerApi implements RateProviderInterface
{
/**
* The Fixer Api access_key
*
* @var string
*/
public $access_key;
/**
* Yii http client
*
* @var Client
*/
private $_client;
/**
* Create a new provider instance.
*
* @param string $access_key
* @return void
*/
public function __construct($access_key)
{
$this->access_key = $access_key;
$this->_client = new Client([
'baseUrl' => 'https://data.fixer.io',
'transport' => 'yii\httpclient\CurlTransport',
]);
}
/**
* @inheritDoc
*/
public function getRate($source, $target)
{
try {
$response = $this->_client->get('/api/latest', [
'access_key' => $this->access_key,
'base' => $source,
])->send();
$content = $response->getData();
if ($response->isOk && $content['success']) {
return $content['rates'][$target];
}
throw new InvalidConfigException($content['error']['info']);
} catch (\Exception $ex) {
throw $ex;
}
}
}