CalculatorFactory::getCalculator()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 14
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 4

Importance

Changes 0
Metric Value
eloc 7
dl 0
loc 14
ccs 7
cts 7
cp 1
rs 10
c 0
b 0
f 0
cc 4
nc 4
nop 0
crap 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