1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Gacela\Resolver; |
6
|
|
|
|
7
|
|
|
use Psr\Container\ContainerInterface; |
8
|
|
|
|
9
|
|
|
use function is_object; |
10
|
|
|
|
11
|
|
|
final class Container implements ContainerInterface |
12
|
|
|
{ |
13
|
|
|
private ?DependencyResolver $dependencyResolver = null; |
14
|
|
|
|
15
|
|
|
/** @var array<class-string,list<mixed>> */ |
16
|
|
|
private array $cachedDependencies = []; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @param array<class-string, class-string|callable|object> $bindings |
|
|
|
|
20
|
|
|
*/ |
21
|
8 |
|
public function __construct( |
22
|
|
|
private array $bindings = [], |
23
|
|
|
) { |
24
|
8 |
|
} |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @param class-string $className |
28
|
|
|
*/ |
29
|
2 |
|
public static function create(string $className): ?object |
30
|
|
|
{ |
31
|
2 |
|
return (new self())->get($className); |
32
|
|
|
} |
33
|
|
|
|
34
|
2 |
|
public function has(string $id): bool |
35
|
|
|
{ |
36
|
2 |
|
return is_object($this->get($id)); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @param class-string $className |
41
|
|
|
* |
42
|
|
|
* @deprecated Use method 'get(string $id)' instead |
43
|
|
|
*/ |
44
|
|
|
public function createByClassName(string $className): ?object |
45
|
|
|
{ |
46
|
|
|
return $this->get($className); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param class-string|string $id |
51
|
|
|
*/ |
52
|
8 |
|
public function get(string $id): ?object |
53
|
|
|
{ |
54
|
8 |
|
if (class_exists($id)) { |
55
|
7 |
|
if (!isset($this->cachedDependencies[$id])) { |
56
|
7 |
|
$this->cachedDependencies[$id] = $this |
57
|
7 |
|
->getDependencyResolver() |
58
|
7 |
|
->resolveDependencies($id); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
/** @psalm-suppress MixedMethodCall */ |
62
|
7 |
|
return new $id(...$this->cachedDependencies[$id]); |
63
|
|
|
} |
64
|
|
|
|
65
|
1 |
|
return null; |
66
|
|
|
} |
67
|
|
|
|
68
|
7 |
|
private function getDependencyResolver(): DependencyResolver |
69
|
|
|
{ |
70
|
7 |
|
if ($this->dependencyResolver === null) { |
71
|
7 |
|
$this->dependencyResolver = new DependencyResolver( |
72
|
7 |
|
$this->bindings, |
73
|
7 |
|
); |
74
|
|
|
} |
75
|
|
|
|
76
|
7 |
|
return $this->dependencyResolver; |
|
|
|
|
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|