Completed
Push — master ( 22330a...e8d007 )
by Dmitry
01:58
created

TargetFactory::create()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 10
ccs 0
cts 2
cp 0
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 6
nc 2
nop 1
crap 6
1
<?php
2
3
namespace hiqdev\billing\hiapi\target;
4
5
use hiqdev\billing\hiapi\target\device\ServerTarget;
6
use hiqdev\php\billing\target\Target;
7
use hiqdev\php\billing\target\TargetCreationDto;
8
use hiqdev\php\billing\target\TargetFactoryInterface;
9
use hiqdev\php\units\exceptions\InvalidConfigException;
10
11
class TargetFactory implements TargetFactoryInterface
12
{
13
    /**
14
     * @return Target|null
15
     */
16
    public function create(TargetCreationDto $dto): ?Target
17
    {
18
        if (!isset($dto->type)) {
19
            $class = Target::class;
20
        } else {
21
            $class = $this->getClassForType($dto);
22
        }
23
24
        return new $class($dto->id, $dto->type);
25
    }
26
27
    protected function getClassForType(TargetCreationDto $dto): string
28
    {
29
        $map = [
30
            'device' => [
31
                '*' => ServerTarget::class,
32
            ]
33
        ];
34
35
        $type = $dto->type;
36
        $subtype = '*';
37
38
        if (strpos($type, '.') !== false) {
39
            [$type, $subtype] = explode('.', $type, 2);
40
        }
41
42
        $class = $map[$type][$subtype] ?? $map[$type]['*'] ?? null;
43
44
        if ($class === null) {
45
            throw new InvalidConfigException('No class for type' . $dto->type);
46
        }
47
48
        return $class;
49
    }
50
}
51