Passed
Push — main ( 6979ab...4bfe8a )
by Chema
02:12
created

InstanceCreator   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 43
Duplicated Lines 0 %

Test Coverage

Coverage 93.75%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 43
ccs 15
cts 16
cp 0.9375
rs 10
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A getDependencyResolver() 0 9 2
A createByClassName() 0 14 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gacela\InstanceCreator;
6
7
use Gacela\DependencyResolver\DependencyResolver;
8
9
final class InstanceCreator
10
{
11
    private ?DependencyResolver $dependencyResolver = null;
12
13
    /** @var array<class-string,list<mixed>> */
14
    private array $cachedDependencies = [];
15
16
    /**
17
     * @param array<class-string,class-string|callable|object> $mappingInterfaces
18
     */
19 4
    public function __construct(
20
        private array $mappingInterfaces = [],
21
    ) {
22 4
    }
23
24
    /**
25
     * @param class-string $className
26
     */
27 4
    public function createByClassName(string $className): ?object
28
    {
29 4
        if (class_exists($className)) {
30 4
            if (!isset($this->cachedDependencies[$className])) {
31 4
                $this->cachedDependencies[$className] = $this
32 4
                    ->getDependencyResolver()
33 4
                    ->resolveDependencies($className);
34
            }
35
36
            /** @psalm-suppress MixedMethodCall */
37 4
            return new $className(...$this->cachedDependencies[$className]);
38
        }
39
40
        return null;
41
    }
42
43 4
    private function getDependencyResolver(): DependencyResolver
44
    {
45 4
        if ($this->dependencyResolver === null) {
46 4
            $this->dependencyResolver = new DependencyResolver(
47 4
                $this->mappingInterfaces,
48 4
            );
49
        }
50
51 4
        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\DependencyResolver\DependencyResolver. Consider adding an additional type-check to rule them out.
Loading history...
52
    }
53
}
54