ConverterFactory::createUnitConverter()   A
last analyzed

Complexity

Conditions 5
Paths 4

Size

Total Lines 28

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 5.0592

Importance

Changes 0
Metric Value
dl 0
loc 28
ccs 13
cts 15
cp 0.8667
rs 9.1608
c 0
b 0
f 0
cc 5
nc 4
nop 1
crap 5.0592
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ecocode\SyliusBasePricePlugin\Services;
6
7
use Ecocode\SyliusBasePricePlugin\Exceptions\BadMeasurementException;
8
use InvalidArgumentException;
9
use Twig\Extension\AbstractExtension;
10
use UnitConverter\Measure;
11
use UnitConverter\Unit\UnitInterface;
12
use UnitConverter\UnitConverter;
13
14
/**
15
 * Class Converter
16
 * @package Ecocode\SyliusBasePricePlugin\Services
17
 */
18
class ConverterFactory extends AbstractExtension
19
{
20
    /**
21
     * @param string[] $measurements example: ['UnitConverter\Measure::MASS']
22
     *
23
     * @return UnitConverter
24
     */
25 12
    public static function createUnitConverter(array $measurements = null): UnitConverter
26
    {
27 12
        $converter = UnitConverter::createBuilder();
28 12
        $converter->addSimpleCalculator();
29
30 12
        if ($measurements === null || count($measurements) === 0) {
31
            return $converter->addDefaultRegistry()->build();
32
        }
33
34 12
        $units = [];
35 12
        foreach ($measurements as $const) {
36
            /** @var string|null $measurement */
37 12
            $measurement = constant($const);
38 12
            if ($measurement === null) {
39
                throw new BadMeasurementException('unknown measurement "' . $const . '" given');
40
            }
41
42
            /** @var array<array-key, UnitInterface> $mergeUnits */
43 12
            $mergeUnits = array_map(
44 12
                [__CLASS__, 'classFactory'],
45 12
                Measure::getDefaultUnitsFor($measurement)
46
            );
47
48 12
            $units = array_merge($units, $mergeUnits);
49
        }
50
51 12
        return $converter->addRegistryWith($units)->build();
52
    }
53
54 12
    public static function classFactory(string $class): UnitInterface
55
    {
56 12
        if (class_exists($class)) {
57
            /** @psalm-suppress MixedMethodCall */
58 12
            $object = new $class();
59
60 12
            if (!$object instanceof UnitInterface) {
61
                $message = sprintf('Class %s not instance of UnitInterface', $class);
62
63
                throw new InvalidArgumentException($message);
64
            }
65
66 12
            return $object;
67
        }
68
69
        $message = sprintf('Class %s not found', $class);
70
71
        throw new InvalidArgumentException($message);
72
    }
73
}
74