Factory::getInstance()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 10
nc 5
nop 1
dl 0
loc 16
ccs 10
cts 10
cp 1
crap 4
rs 9.9332
c 1
b 0
f 0
1
<?php
2
3
namespace kalanis\kw_mapper\Mappers;
4
5
6
use kalanis\kw_mapper\MapperException;
7
use ReflectionClass;
8
use ReflectionException;
9
10
11
/**
12
 * Class Factory
13
 * @package kalanis\kw_mapper\Mappers
14
 * Factory for getting available mappers
15
 */
16
class Factory
17
{
18
    /** @var array<string, AMapper> */
19
    protected static array $instances = [];
20
21
    /**
22
     * Which instances of mappers are available
23
     * @param string $path
24
     * @throws MapperException when initialization fails
25
     * @return AMapper
26
     */
27 173
    public function getInstance(string $path): AMapper
28
    {
29 173
        if (!isset(static::$instances[$path])) {
30
            try {
31
                /** @var class-string $path */
32 35
                $reflex = new ReflectionClass($path);
33 34
                $instance = $reflex->newInstance();
34 1
            } catch (ReflectionException $ex) {
35 1
                throw new MapperException(sprintf('Wanted class *%s* does not exists!', $path), $ex->getCode(), $ex);
36
            }
37 34
            if (!$instance instanceof AMapper) {
38 1
                throw new MapperException(sprintf('Defined class *%s* is not instance of AMapper!', $path));
39
            }
40 33
            static::$instances[$path] = $instance;
41
        }
42 171
        return static::$instances[$path];
43
    }
44
}
45