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

CompositeCurrencyConverter   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 8
eloc 15
dl 0
loc 39
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A supports() 0 9 3
A convert() 0 15 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