1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Ksdev\NBPCurrencyConverter; |
4
|
|
|
|
5
|
|
|
class CurrencyConverter |
6
|
|
|
{ |
7
|
|
|
private $ratesTableFinder; |
8
|
|
|
|
9
|
|
|
public function __construct(ExRatesTableFinder $ratesTableFinder) |
10
|
|
|
{ |
11
|
|
|
$this->ratesTableFinder = $ratesTableFinder; |
12
|
|
|
} |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Get the average exchange rates |
16
|
|
|
* |
17
|
|
|
* @param \DateTime $pubDate Optional rates table publication date |
18
|
|
|
* |
19
|
|
|
* @return array |
20
|
|
|
* |
21
|
|
|
* @throws \Exception |
22
|
|
|
*/ |
23
|
|
|
public function averageExchangeRates(\DateTime $pubDate = null) |
24
|
|
|
{ |
25
|
|
|
$ratesTable = $this->ratesTableFinder->getExRatesTable($pubDate); |
26
|
|
|
return $ratesTable->parsedContent; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Convert amount from one currency to another |
31
|
|
|
* |
32
|
|
|
* @param string $fromAmount Amount with four digits after decimal point, e.g. '123.0000' |
33
|
|
|
* @param string $fromCurrency E.g. 'USD' or 'EUR' |
34
|
|
|
* @param string $toCurrency E.g. 'USD' or 'EUR' |
35
|
|
|
* @param \DateTime $pubDate Optional rates table publication date |
36
|
|
|
* |
37
|
|
|
* @return array |
38
|
|
|
* |
39
|
|
|
* @throws \Exception |
40
|
|
|
*/ |
41
|
|
|
public function convert($fromAmount, $fromCurrency, $toCurrency, \DateTime $pubDate = null) |
42
|
|
|
{ |
43
|
|
|
if (!preg_match('/^\d+\.(\d{4})$/', $fromAmount)) { |
44
|
|
|
throw new \Exception('Invalid format of amount'); |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
$rates = $this->averageExchangeRates($pubDate); |
48
|
|
|
|
49
|
|
|
$fromCurrency = strtoupper($fromCurrency); |
50
|
|
|
$toCurrency = strtoupper($toCurrency); |
51
|
|
|
if (!isset($rates['waluty'][$fromCurrency]) || !isset($rates['waluty'][$toCurrency])) { |
52
|
|
|
throw new \Exception('Invalid currency code'); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
$fromMultiplier = str_replace(',', '.', $rates['waluty'][$fromCurrency]['przelicznik']); |
56
|
|
|
$fromAverageRate = str_replace(',', '.', $rates['waluty'][$fromCurrency]['kurs_sredni']); |
57
|
|
|
$toMultiplier = str_replace(',', '.', $rates['waluty'][$toCurrency]['przelicznik']); |
58
|
|
|
$toAverageRate = str_replace(',', '.', $rates['waluty'][$toCurrency]['kurs_sredni']); |
59
|
|
|
|
60
|
|
|
bcscale(20); |
61
|
|
|
$plnAmount = bcdiv(bcmul($fromAmount, $fromAverageRate), $fromMultiplier); |
62
|
|
|
$resultAmount = bcdiv(bcmul($plnAmount, $toMultiplier), $toAverageRate); |
63
|
|
|
$roundedResult = BCMathHelper::bcround($resultAmount, 4); |
64
|
|
|
|
65
|
|
|
return [ |
66
|
|
|
'publication_date' => $rates['data_publikacji'], |
67
|
|
|
'amount' => $roundedResult, |
68
|
|
|
'currency' => $toCurrency |
69
|
|
|
]; |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
|