|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Gacela\Container; |
|
6
|
|
|
|
|
7
|
|
|
use RuntimeException; |
|
8
|
|
|
|
|
9
|
|
|
use function is_array; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* Builder for creating contextual bindings. |
|
13
|
|
|
* Allows different concrete implementations based on the requesting class. |
|
14
|
|
|
*/ |
|
15
|
|
|
final class ContextualBindingBuilder |
|
16
|
|
|
{ |
|
17
|
|
|
/** @var list<class-string> */ |
|
18
|
|
|
private array $concrete = []; |
|
19
|
|
|
|
|
20
|
|
|
private ?string $needs = null; |
|
21
|
|
|
|
|
22
|
|
|
/** |
|
23
|
|
|
* @param array<string, array<class-string, class-string|callable|object>> $contextualBindings |
|
|
|
|
|
|
24
|
|
|
*/ |
|
25
|
5 |
|
public function __construct( |
|
26
|
|
|
private array &$contextualBindings, |
|
27
|
|
|
) { |
|
28
|
5 |
|
} |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* Define which class(es) this binding applies to. |
|
32
|
|
|
* |
|
33
|
|
|
* @param class-string|list<class-string> $concrete |
|
|
|
|
|
|
34
|
|
|
*/ |
|
35
|
5 |
|
public function when(string|array $concrete): self |
|
36
|
|
|
{ |
|
37
|
5 |
|
$this->concrete = is_array($concrete) ? $concrete : [$concrete]; |
|
|
|
|
|
|
38
|
|
|
|
|
39
|
5 |
|
return $this; |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
|
|
/** |
|
43
|
|
|
* Define which dependency to bind. |
|
44
|
|
|
* |
|
45
|
|
|
* @param class-string $abstract |
|
46
|
|
|
*/ |
|
47
|
5 |
|
public function needs(string $abstract): self |
|
48
|
|
|
{ |
|
49
|
5 |
|
$this->needs = $abstract; |
|
50
|
|
|
|
|
51
|
5 |
|
return $this; |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
/** |
|
55
|
|
|
* Define what to give when the dependency is needed. |
|
56
|
|
|
* |
|
57
|
|
|
* @param class-string|callable|object $implementation |
|
|
|
|
|
|
58
|
|
|
*/ |
|
59
|
5 |
|
public function give(mixed $implementation): void |
|
60
|
|
|
{ |
|
61
|
5 |
|
if ($this->needs === null) { |
|
62
|
|
|
throw new RuntimeException('Must call needs() before give()'); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
5 |
|
foreach ($this->concrete as $concreteClass) { |
|
66
|
5 |
|
if (!isset($this->contextualBindings[$concreteClass])) { |
|
67
|
|
|
/** @psalm-suppress PropertyTypeCoercion */ |
|
68
|
5 |
|
$this->contextualBindings[$concreteClass] = []; |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
/** |
|
72
|
|
|
* @psalm-suppress PropertyTypeCoercion |
|
73
|
|
|
* |
|
74
|
|
|
* @phpstan-ignore assign.propertyType |
|
75
|
|
|
*/ |
|
76
|
5 |
|
$this->contextualBindings[$concreteClass][$this->needs] = $implementation; |
|
77
|
|
|
} |
|
78
|
|
|
} |
|
79
|
|
|
} |
|
80
|
|
|
|