Passed
Push — remove-custom-container ( 1805fb...36702b )
by Chema
03:10
created

Locator::newInstance()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 1
dl 0
loc 8
ccs 4
cts 4
cp 1
crap 2
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 3
    public static function getInstance(): self
29
    {
30 3
        if (self::$instance === null) {
31 3
            self::$instance = new self();
32
        }
33
34 3
        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...
35
    }
36
37 2
    public static function resetInstance(): void
38
    {
39 2
        self::$instance = null;
40
    }
41
42
    /**
43
     * @template T
44
     *
45
     * @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...
46
     *
47
     * @return T|null
48
     */
49 3
    public function get(string $className)
50
    {
51 3
        if (isset($this->instanceCache[$className])) {
52
            /** @var T $instance */
53 1
            $instance = $this->instanceCache[$className];
54
55 1
            return $instance;
56
        }
57
58
        /** @var T|null $locatedInstance */
59 3
        $locatedInstance = AnonymousGlobal::getByClassName($className)
60 3
            ?? GacelaContainer::create($className);
61
62
        /** @psalm-suppress MixedAssignment */
63 3
        $this->instanceCache[$className] = $locatedInstance;
64
65 3
        return $locatedInstance;
66
    }
67
}
68