Passed
Push — add-pre-plugins ( a890af )
by Chema
03:45
created

Locator   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 16
dl 0
loc 63
ccs 19
cts 19
cp 1
rs 10
c 0
b 0
f 0
wmc 8

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A __clone() 0 2 1
A resetInstance() 0 3 1
A add() 0 5 1
A getInstance() 0 7 2
A get() 0 17 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Gacela\Framework\Container;
6
7
use Gacela\Container\Container as GacelaContainer;
8
use Gacela\Framework\ClassResolver\GlobalInstance\AnonymousGlobal;
9
10
final class Locator
11
{
12
    private static ?Locator $instance = null;
13
14
    /** @var array<string, mixed> */
15
    private array $instanceCache = [];
16
17 3
    private function __construct()
18
    {
19 3
    }
20
21
    /**
22
     * @codeCoverageIgnore
23
     */
24
    private function __clone()
25
    {
26
    }
27
28 1
    public function add(string $className, mixed $instance): self
29
    {
30 1
        $this->instanceCache[$className] = $instance;
31
32 1
        return $this;
33
    }
34
35 4
    public static function getInstance(): self
36
    {
37 4
        if (self::$instance === null) {
38 3
            self::$instance = new self();
39
        }
40
41 4
        return self::$instance;
0 ignored issues
show
Bug Best Practice introduced by
The expression return self::instance could return the type null which is incompatible with the type-hinted return Gacela\Framework\Container\Locator. Consider adding an additional type-check to rule them out.
Loading history...
42
    }
43
44 2
    public static function resetInstance(): void
45
    {
46 2
        self::$instance = null;
47
    }
48
49
    /**
50
     * @template T
51
     *
52
     * @param class-string<T> $className
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string<T> at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string<T>.
Loading history...
53
     *
54
     * @return T|null
55
     */
56 4
    public function get(string $className)
57
    {
58 4
        if (isset($this->instanceCache[$className])) {
59
            /** @var T $instance */
60 2
            $instance = $this->instanceCache[$className];
61
62 2
            return $instance;
63
        }
64
65
        /** @var T|null $locatedInstance */
66 3
        $locatedInstance = AnonymousGlobal::getByClassName($className)
67 3
            ?? GacelaContainer::create($className);
68
69
        /** @psalm-suppress MixedAssignment */
70 3
        $this->instanceCache[$className] = $locatedInstance;
71
72 3
        return $locatedInstance;
73
    }
74
}
75