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\Service; |
13
|
|
|
|
14
|
|
|
use ONGR\CurrencyExchangeBundle\Exception\UndefinedCurrencyException; |
15
|
|
|
|
16
|
|
|
/** |
17
|
|
|
* This class handles currency rates download and exchange. |
18
|
|
|
*/ |
19
|
|
|
class CurrencyExchangeService |
20
|
|
|
{ |
21
|
|
|
/** |
22
|
|
|
* @var CurrencyRatesService |
23
|
|
|
*/ |
24
|
|
|
private $rates = null; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @var string |
28
|
|
|
*/ |
29
|
|
|
private $defaultCurrency; |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @param CurrencyRatesService $rates |
33
|
|
|
* @param string $defaultCurrency |
34
|
|
|
*/ |
35
|
31 |
|
public function __construct(CurrencyRatesService $rates, $defaultCurrency) |
36
|
|
|
{ |
37
|
31 |
|
$this->rates = $rates; |
38
|
31 |
|
$this->defaultCurrency = $defaultCurrency; |
39
|
31 |
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @param string $currency |
43
|
|
|
* @param string|null $date |
44
|
|
|
* |
45
|
|
|
* @throws UndefinedCurrencyException |
46
|
|
|
* |
47
|
|
|
* @return float |
48
|
29 |
|
*/ |
49
|
|
|
public function getCurrencyRate($currency, $date = null) |
50
|
29 |
|
{ |
51
|
|
|
$rates = $this->rates->getRates($date); |
52
|
29 |
|
|
53
|
27 |
|
if (isset($rates[$currency])) { |
54
|
|
|
return $rates[$currency]; |
55
|
|
|
} |
56
|
2 |
|
|
57
|
|
|
throw new UndefinedCurrencyException('Currency ' . $currency . ' not found.'); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* @return array|null |
62
|
1 |
|
*/ |
63
|
|
|
public function getCurrencies() |
64
|
1 |
|
{ |
65
|
|
|
return $this->rates->getRates(); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* This function calculate rates. |
70
|
|
|
* |
71
|
|
|
* @param float|int $amount |
72
|
|
|
* @param string $toCurrency |
73
|
|
|
* @param null $fromCurrency |
74
|
|
|
* @param string|null $date |
75
|
|
|
* |
76
|
28 |
|
* @return float |
77
|
|
|
*/ |
78
|
28 |
|
public function calculateRate($amount, $toCurrency, $fromCurrency = null, $date = null) |
79
|
17 |
|
{ |
80
|
17 |
|
if (!isset($fromCurrency)) { |
81
|
|
|
$fromCurrency = $this->defaultCurrency; |
82
|
28 |
|
} |
83
|
28 |
|
|
84
|
27 |
|
if ($this->rates->getBaseCurrency() != $fromCurrency) { |
85
|
|
|
$amount = $amount / $this->getCurrencyRate($fromCurrency, $date); |
86
|
27 |
|
} |
87
|
|
|
|
88
|
|
|
if ($toCurrency == $this->rates->getBaseCurrency()) { |
89
|
|
|
return $amount; |
90
|
27 |
|
} |
91
|
|
|
|
92
|
|
|
return $amount * $this->getCurrencyRate($toCurrency, $date); |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
|