|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Gacela\Container; |
|
6
|
|
|
|
|
7
|
|
|
use function class_exists; |
|
8
|
|
|
use function is_callable; |
|
9
|
|
|
use function is_object; |
|
10
|
|
|
use function is_string; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* Resolves abstract types to concrete implementations using bindings. |
|
14
|
|
|
*/ |
|
15
|
|
|
final class BindingResolver |
|
16
|
|
|
{ |
|
17
|
|
|
/** |
|
18
|
|
|
* @param array<class-string, class-string|callable|object> $bindings |
|
19
|
|
|
*/ |
|
20
|
|
|
public function __construct( |
|
21
|
|
|
private array $bindings = [], |
|
22
|
|
|
) { |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* Resolve a class to a concrete instance using bindings. |
|
27
|
|
|
*/ |
|
28
|
|
|
public function resolve(string $class, DependencyCacheManager $cacheManager): ?object |
|
29
|
|
|
{ |
|
30
|
|
|
if (isset($this->bindings[$class])) { |
|
31
|
|
|
$binding = $this->bindings[$class]; |
|
32
|
|
|
|
|
33
|
|
|
if (is_callable($binding)) { |
|
34
|
|
|
/** @var mixed $binding */ |
|
35
|
|
|
$binding = $binding(); |
|
36
|
|
|
} |
|
37
|
|
|
|
|
38
|
|
|
if (is_object($binding)) { |
|
39
|
|
|
return $binding; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** @var class-string $binding */ |
|
43
|
|
|
if (class_exists($binding)) { |
|
44
|
|
|
return $cacheManager->instantiate($binding); |
|
45
|
|
|
} |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
if (class_exists($class)) { |
|
49
|
|
|
return $cacheManager->instantiate($class); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
return null; |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
/** |
|
56
|
|
|
* Check if a binding exists for a class. |
|
57
|
|
|
*/ |
|
58
|
|
|
public function hasBinding(string $class): bool |
|
59
|
|
|
{ |
|
60
|
|
|
return isset($this->bindings[$class]); |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
/** |
|
64
|
|
|
* Get all bindings. |
|
65
|
|
|
* |
|
66
|
|
|
* @return array<class-string, class-string|callable|object> |
|
67
|
|
|
*/ |
|
68
|
|
|
public function getBindings(): array |
|
69
|
|
|
{ |
|
70
|
|
|
return $this->bindings; |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
/** |
|
74
|
|
|
* Resolve a type name to its concrete implementation (for dependency analysis). |
|
75
|
|
|
* |
|
76
|
|
|
* @param class-string $typeName |
|
77
|
|
|
* |
|
78
|
|
|
* @return class-string |
|
79
|
|
|
*/ |
|
80
|
|
|
public function resolveType(string $typeName): string |
|
81
|
|
|
{ |
|
82
|
|
|
if (isset($this->bindings[$typeName])) { |
|
83
|
|
|
$binding = $this->bindings[$typeName]; |
|
84
|
|
|
|
|
85
|
|
|
if (is_string($binding) && class_exists($binding)) { |
|
86
|
|
|
/** @var class-string */ |
|
87
|
|
|
return $binding; |
|
88
|
|
|
} |
|
89
|
|
|
} |
|
90
|
|
|
|
|
91
|
|
|
return $typeName; |
|
92
|
|
|
} |
|
93
|
|
|
} |
|
94
|
|
|
|