Passed
Push — main ( 3246f4...4c0521 )
by Vasil
02:31
created

Shipping::canCreate()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 5
nc 3
nop 1
dl 0
loc 11
ccs 6
cts 6
cp 1
crap 3
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
class Shipping implements ShippingInterface
18
{
19 4
    public static function create(string $name): AdapterInterface
20
    {
21 4
        $class = static::getClassName($name);
22 4
        if (! static::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
        // If the class starts with \ or Omnipay\, assume it's a FQCN
47
        /*if (str_starts_with($name, '\\') || str_starts_with($name, 'Shipping\\Adapter\\')) {
48
            return $name;
49
        }*/
50
51 4
        if (0 === strpos($name, '\\') || 0 === strpos($name, 'VasilDakov\\Shipping\\Adapter\\')) {
52 2
            return $name;
53
        }
54
55 2
        return '\\VasilDakov\\Shipping\\Adapter\\' . $name . 'Adapter';
56
    }
57
}
58