Completed
Push — master ( b9260b...b1a7da )
by Joachim
06:19
created

CompositeCurrencyConverter::convert()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 15
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 8
dl 0
loc 15
rs 10
c 0
b 0
f 0
cc 4
nc 4
nop 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Setono\SyliusStockMovementPlugin\CurrencyConverter;
6
7
use Money\Money;
8
use Safe\Exceptions\StringsException;
9
use Setono\SyliusStockMovementPlugin\Exception\CurrencyConversionException;
10
11
final class CompositeCurrencyConverter extends CurrencyConverter
12
{
13
    /** @var CurrencyConverterInterface[] */
14
    private $currencyConverters;
15
16
    public function __construct(CurrencyConverterInterface ...$currencyConverters)
17
    {
18
        $this->currencyConverters = $currencyConverters;
19
    }
20
21
    /**
22
     * @throws StringsException
23
     */
24
    public function convert(int $amount, string $sourceCurrency, string $targetCurrency, array $conversionContext = []): Money
25
    {
26
        foreach ($this->currencyConverters as $currencyConverter) {
27
            if (!$currencyConverter->supports($amount, $sourceCurrency, $targetCurrency, $conversionContext)) {
28
                continue;
29
            }
30
31
            try {
32
                return $currencyConverter->convert($amount, $sourceCurrency, $targetCurrency, $conversionContext);
33
            } catch (CurrencyConversionException $e) {
34
                continue;
35
            }
36
        }
37
38
        throw new CurrencyConversionException($amount, $sourceCurrency, $targetCurrency, $conversionContext);
39
    }
40
41
    public function supports(int $amount, string $sourceCurrency, string $targetCurrency, array $conversionContext = []): bool
42
    {
43
        foreach ($this->currencyConverters as $currencyConverter) {
44
            if ($currencyConverter->supports($amount, $sourceCurrency, $targetCurrency, $conversionContext)) {
45
                return true;
46
            }
47
        }
48
49
        return false;
50
    }
51
}
52