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

TargetFactory   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 2

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
wmc 5
lcom 0
cbo 2
dl 0
loc 40
ccs 0
cts 22
cp 0
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A create() 0 10 2
A getClassForType() 0 23 3
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