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
|
5 |
|
private function __construct() |
18
|
|
|
{ |
19
|
5 |
|
} |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @codeCoverageIgnore |
23
|
|
|
*/ |
24
|
|
|
private function __clone() |
25
|
|
|
{ |
26
|
|
|
} |
27
|
|
|
|
28
|
4 |
|
public static function resetInstance(): void |
29
|
|
|
{ |
30
|
4 |
|
self::$instance = null; |
31
|
|
|
} |
32
|
|
|
|
33
|
2 |
|
public static function addSingleton(string $key, mixed $value): void |
34
|
|
|
{ |
35
|
2 |
|
self::getInstance()->add($key, $value); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @template T |
40
|
|
|
* |
41
|
|
|
* @param class-string<T> $className |
|
|
|
|
42
|
|
|
* |
43
|
|
|
* @return T|null |
44
|
|
|
*/ |
45
|
3 |
|
public static function getSingleton(string $className) |
46
|
|
|
{ |
47
|
3 |
|
return self::getInstance()->get($className); |
48
|
|
|
} |
49
|
|
|
|
50
|
6 |
|
public static function getInstance(): self |
51
|
|
|
{ |
52
|
6 |
|
if (self::$instance === null) { |
53
|
5 |
|
self::$instance = new self(); |
54
|
|
|
} |
55
|
|
|
|
56
|
6 |
|
return self::$instance; |
|
|
|
|
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* @template T |
61
|
|
|
* |
62
|
|
|
* @param class-string<T> $className |
|
|
|
|
63
|
|
|
* |
64
|
|
|
* @return T|null |
65
|
|
|
*/ |
66
|
6 |
|
public function get(string $className) |
67
|
|
|
{ |
68
|
6 |
|
if (isset($this->instanceCache[$className])) { |
69
|
|
|
/** @var T $instance */ |
70
|
3 |
|
$instance = $this->instanceCache[$className]; |
71
|
|
|
|
72
|
3 |
|
return $instance; |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
/** @var T|null $locatedInstance */ |
76
|
4 |
|
$locatedInstance = AnonymousGlobal::getByClassName($className) |
77
|
4 |
|
?? GacelaContainer::create($className); |
78
|
|
|
|
79
|
|
|
/** @psalm-suppress MixedAssignment */ |
80
|
4 |
|
$this->instanceCache[$className] = $locatedInstance; |
81
|
|
|
|
82
|
4 |
|
return $locatedInstance; |
83
|
|
|
} |
84
|
|
|
|
85
|
2 |
|
private function add(string $key, mixed $value): self |
86
|
|
|
{ |
87
|
2 |
|
$this->instanceCache[$key] = $value; |
88
|
|
|
|
89
|
2 |
|
return $this; |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|