1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace BenTools\Currency\Tests\Provider; |
4
|
|
|
|
5
|
|
|
use BenTools\Currency\Model\Currency; |
6
|
|
|
use BenTools\Currency\Model\ExchangeRateInterface; |
7
|
|
|
use BenTools\Currency\Provider\AverageExchangeRateProvider; |
8
|
|
|
use BenTools\Currency\Tests\ProviderMockTrait; |
9
|
|
|
use PHPUnit\Framework\TestCase; |
10
|
|
|
|
11
|
|
|
class AverageExchangeRateProviderTest extends TestCase |
12
|
|
|
{ |
13
|
|
|
use ProviderMockTrait; |
14
|
|
|
|
15
|
|
|
public function testGetExchangeRate() |
16
|
|
|
{ |
17
|
|
|
|
18
|
|
|
$numberOfProviders = random_int(3, 10); |
19
|
|
|
$ratios = []; |
20
|
|
|
for ($i = 1; $i <= $numberOfProviders; $i++) { |
21
|
|
|
$ratios[] = $ratio = $this->generateFakeRatio(); |
22
|
|
|
$providers[] = $this->generateFakeProvider($ratio); |
|
|
|
|
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
$provider = AverageExchangeRateProvider::create()->withProviders(...$providers); |
|
|
|
|
26
|
|
|
|
27
|
|
|
$averageRatio = array_sum($ratios) / count($ratios); |
28
|
|
|
$exchangeRate = $provider->getExchangeRate(new Currency('EUR'), new Currency('USD')); |
29
|
|
|
$this->assertInstanceOf(ExchangeRateInterface::class, $exchangeRate); |
30
|
|
|
$this->assertEquals($averageRatio, $exchangeRate->getRatio()); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function testPrecision() |
34
|
|
|
{ |
35
|
|
|
$provider = AverageExchangeRateProvider::create(0.02)->withProviders( |
36
|
|
|
$this->generateFakeProvider(1.12), |
37
|
|
|
$this->generateFakeProvider(1.13) |
38
|
|
|
); |
39
|
|
|
$exchangeRate = $provider->getExchangeRate(new Currency('EUR'), new Currency('USD')); |
40
|
|
|
$this->assertEquals(1.125, $exchangeRate->getRatio()); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @expectedException \RuntimeException |
45
|
|
|
* @expectedExceptionMessage Tolerance fault: 0.03 difference between minimum and maximum ratio, 0.02 allowed. |
46
|
|
|
*/ |
47
|
|
|
public function testPrecisionFails() |
48
|
|
|
{ |
49
|
|
|
$provider = AverageExchangeRateProvider::create(0.02)->withProviders( |
50
|
|
|
$this->generateFakeProvider(1.10), |
51
|
|
|
$this->generateFakeProvider(1.13) |
52
|
|
|
); |
53
|
|
|
$exchangeRate = $provider->getExchangeRate(new Currency('EUR'), new Currency('USD')); |
|
|
|
|
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
} |
57
|
|
|
|
Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.
Let’s take a look at an example:
As you can see in this example, the array
$myArray
is initialized the first time when the foreach loop is entered. You can also see that the value of thebar
key is only written conditionally; thus, its value might result from a previous iteration.This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.