Passed
Push — master ( 309dcb...6acad1 )
by Petr
02:25
created

Factory::fromPairs()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 4

Importance

Changes 0
Metric Value
cc 4
eloc 7
c 0
b 0
f 0
nc 4
nop 1
dl 0
loc 12
rs 10
ccs 8
cts 8
cp 1
crap 4
1
<?php
2
3
namespace kalanis\kw_storage\Storage\Target;
4
5
6
use kalanis\kw_storage\Interfaces;
7
8
9
/**
10
 * Class Factory
11
 * @package kalanis\kw_storage\Storage\Target
12
 * Simple example of storage factory
13
 */
14
class Factory
15
{
16
    /** @var array<string, string|null> */
17
    protected static $pairs = [
18
        'mem' => Memory::class,
19
        'memory' => Memory::class,
20
        'vol' => Volume::class,
21
        'volume' => Volume::class,
22
        'volume::flat' => VolumeTargetFlat::class,
23
        'volume::stream' => VolumeStream::class,
24
        'local' => Volume::class,
25
        'local::flat' => VolumeTargetFlat::class,
26
        'local::stream' => VolumeStream::class,
27
        'drive' => Volume::class,
28
        'drive::flat' => VolumeTargetFlat::class,
29
        'drive::stream' => VolumeStream::class,
30
        'none' => null,
31
    ];
32
33
    /**
34
     * @param mixed|object|array|string|null $params
35
     * @return Interfaces\ITarget|null storage adapter or empty for no storage set
36
     */
37 33
    public function getStorage($params): ?Interfaces\ITarget
38
    {
39 33
        if ($params instanceof Interfaces\ITarget) {
40 2
            return $params;
41
        }
42
43 32
        if (is_array($params)) {
44 14
            if (isset($params['storage'])) {
45 13
                return $this->fromPairs(strval($params['storage']));
46
            }
47
        }
48
49 19
        if (is_string($params)) {
50 16
            return $this->fromPairs(strval($params));
51
        }
52 3
        return null;
53
    }
54
55 29
    protected function fromPairs(string $name): ?Interfaces\ITarget
56
    {
57 29
        if (isset(static::$pairs[$name])) {
58 25
            $class = static::$pairs[$name];
59 25
            if (is_string($class)) {
60 25
                $obj = new $class();
61 25
                if ($obj instanceof Interfaces\ITarget) {
62 25
                    return $obj;
63
                }
64
            }
65
        }
66 4
        return null;
67
    }
68
}
69