CalculatorFactory   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 6
eloc 15
dl 0
loc 37
ccs 11
cts 11
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A registerCalculator() 0 7 2
A getCalculator() 0 14 4
1
<?php
2
/**
3
 * Date: 09.11.18
4
 * Time: 16:06
5
 */
6
7
namespace AlecRabbit\Money;
8
9
use AlecRabbit\Money\Calculator\BcMathCalculator;
10
use AlecRabbit\Money\Contracts\CalculatorInterface;
11
12
class CalculatorFactory
13
{
14
    /** @var array */
15
    private static $calculators = [
16
        BcMathCalculator::class,
17
    ];
18
19
    /** @var null|CalculatorInterface */
20
    private static $calculator;
21
22 145
    public static function getCalculator(): CalculatorInterface
23
    {
24 145
        if (null !== self::$calculator) {
25 143
            return self::$calculator;
26
        }
27 2
        foreach (self::$calculators as $calculator) {
28
            /** @var CalculatorInterface $calculator */
29 1
            if ($calculator::supported()) {
30
                return
31 1
                    self::$calculator = new $calculator();
32
            }
33
        }
34
35 1
        throw new \RuntimeException('Cannot find calculator for money calculations.');
36
    }
37
38
    /**
39
     * @param string $calculator
40
     * @return int
41
     */
42 2
    public static function registerCalculator($calculator): int
43
    {
44 2
        if (is_a($calculator, CalculatorInterface::class, true) === false) {
45 1
            throw new \InvalidArgumentException('Calculator must implement [' . CalculatorInterface::class . '].');
46
        }
47
        return
48 1
            array_unshift(self::$calculators, $calculator);
49
    }
50
}
51