Shipping::create()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 10
ccs 5
cts 5
cp 1
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace VasilDakov\Shipping;
6
7
use VasilDakov\Shipping\Adapter\AdapterInterface;
8
use VasilDakov\Shipping\Exception\RuntimeException;
9
10
/**
11
 * Class Shipping
12
 *
13
 * @author    Vasil Dakov <[email protected]>
14
 * @copyright 2009-2024 Neutrino.bg
15
 * @version   1.0
16
 */
17
final class Shipping implements ShippingInterface
18
{
19 4
    public static function create(string $name): AdapterInterface
20
    {
21 4
        $class = Shipping::getClassName($name);
22 4
        if (! Shipping::canCreate($class)) {
23
            // throw new RuntimeException("Class '$class' not found");
24 2
            throw new RuntimeException("Invalid or non existing adapter");
25
        }
26
27
        // this should be an adapter instance
28 2
        return new $class();
29
    }
30
31 4
    private static function canCreate(string $name): bool
32
    {
33 4
        if (! class_exists($name)) {
34 1
            return false;
35
        }
36
37 3
        if (! is_subclass_of($name, AdapterInterface::class, true)) {
38 1
            return false;
39
        }
40
41 2
        return true;
42
    }
43
44 4
    private static function getClassName(string $name): string
45
    {
46 4
        if (0 === strpos($name, '\\') || 0 === strpos($name, 'VasilDakov\\Shipping\\Adapter\\')) {
47 2
            return $name;
48
        }
49
50 2
        return '\\VasilDakov\\Shipping\\Adapter\\' . $name . 'Adapter';
51
    }
52
}
53