Passed
Push — main ( 15c9ec...2a9479 )
by Chema
55s queued 13s
created

InstanceCreator::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
ccs 2
cts 2
cp 1
crap 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gacela\Resolver;
6
7
final class InstanceCreator
8
{
9
    private ?DependencyResolver $dependencyResolver = null;
10
11
    /** @var array<class-string,list<mixed>> */
12
    private array $cachedDependencies = [];
13
14
    /**
15
     * @param array<class-string,class-string|callable|object> $mappingInterfaces
16
     */
17 6
    public function __construct(
18
        private array $mappingInterfaces = [],
19
    ) {
20 6
    }
21
22
    /**
23
     * @param class-string $className
24
     */
25 2
    public static function create(string $className): ?object
26
    {
27 2
        return (new self())->createByClassName($className);
28
    }
29
30
    /**
31
     * @param class-string $className
32
     */
33 6
    public function createByClassName(string $className): ?object
34
    {
35 6
        if (class_exists($className)) {
36 6
            if (!isset($this->cachedDependencies[$className])) {
37 6
                $this->cachedDependencies[$className] = $this
38 6
                    ->getDependencyResolver()
39 6
                    ->resolveDependencies($className);
40
            }
41
42
            /** @psalm-suppress MixedMethodCall */
43 6
            return new $className(...$this->cachedDependencies[$className]);
44
        }
45
46
        return null;
47
    }
48
49 6
    private function getDependencyResolver(): DependencyResolver
50
    {
51 6
        if ($this->dependencyResolver === null) {
52 6
            $this->dependencyResolver = new DependencyResolver(
53 6
                $this->mappingInterfaces,
54 6
            );
55
        }
56
57 6
        return $this->dependencyResolver;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->dependencyResolver could return the type null which is incompatible with the type-hinted return Gacela\Resolver\DependencyResolver. Consider adding an additional type-check to rule them out.
Loading history...
58
    }
59
}
60