DocumentPartReflectFactory::getPart()   A
last analyzed

Complexity

Conditions 5
Paths 5

Size

Total Lines 29
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 5

Importance

Changes 0
Metric Value
eloc 15
dl 0
loc 29
c 0
b 0
f 0
ccs 13
cts 13
cp 1
rs 9.4555
cc 5
nc 5
nop 2
crap 5
1
<?php
2
3
namespace kalanis\Pohoda\DI;
4
5
use kalanis\Pohoda\Document;
6
use kalanis\PohodaException;
7
use ReflectionClass;
8
use ReflectionException;
9
10
final class DocumentPartReflectFactory implements DocumentPartFactoryInterface
11
{
12 59
    public function __construct(
13
        protected readonly DependenciesFactory $dependenciesFactory,
14 59
    ) {}
15
16
    /**
17
     * {@inheritDoc}
18
     */
19 59
    public function getPart(string $parentClass, string $name): Document\AbstractPart
20
    {
21
        /** @var class-string<Document\AbstractPart> $className */
22 59
        $className = $parentClass . '\\' . $name;
23
        try {
24 59
            $reflection = new ReflectionClass($className);
25 1
        } catch (ReflectionException) {
26 1
            throw new PohodaException('Entity does not exists: ' . $name);
27
        }
28
29 58
        if (!$reflection->isInstantiable()) {
30 2
            throw new PohodaException('Entity cannot be initialized: ' . $name);
31
        }
32
33
        try {
34 56
            $instance = $reflection->newInstance(
35 56
                $this->dependenciesFactory,
36 56
            );
37
            // @codeCoverageIgnoreStart
38
        } catch (ReflectionException) {
39
            throw new PohodaException('Entity initialization failed: ' . $name);
40
        }
41
        // @codeCoverageIgnoreEnd
42
43 56
        if (!is_a($instance, Document\AbstractPart::class)) {
44 1
            throw new PohodaException('Entity is not an instance of AbstractPart: ' . $name);
45
        }
46
47 55
        return $instance;
48
    }
49
}
50