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

InstanceCreator   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 51
Duplicated Lines 0 %

Test Coverage

Coverage 94.44%

Importance

Changes 0
Metric Value
eloc 15
c 0
b 0
f 0
dl 0
loc 51
rs 10
ccs 17
cts 18
cp 0.9444
wmc 7

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A create() 0 3 1
A createByClassName() 0 14 3
A getDependencyResolver() 0 9 2
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