Test Failed
Push — master ( 0864dc...48ec37 )
by Petr
12:45
created

DocumentPartReflectFactory::getPart()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 29
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

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