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

Locator::add()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 5
ccs 3
cts 3
cp 1
crap 1
rs 10
c 0
b 0
f 0
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