1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Ray\Di; |
6
|
|
|
|
7
|
|
|
use Ray\Di\MultiBinding\Lazy; |
8
|
|
|
use Ray\Di\MultiBinding\LazyCollection; |
9
|
|
|
|
10
|
|
|
final class MultiBinder |
11
|
|
|
{ |
12
|
|
|
/** @var Container */ |
13
|
|
|
private $container; |
14
|
|
|
|
15
|
|
|
/** @var array<string, array<int|string, Lazy<object>>> */ |
|
|
|
|
16
|
|
|
private $lazyCollection = []; |
17
|
|
|
|
18
|
|
|
/** @var string */ |
19
|
|
|
private $interface; |
20
|
|
|
|
21
|
|
|
private function __construct(AbstractModule $module, string $interface) |
22
|
|
|
{ |
23
|
|
|
$this->container = $module->getContainer(); |
24
|
|
|
$this->interface = $interface; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
public static function newInstance(AbstractModule $module, string $interface): self |
28
|
|
|
{ |
29
|
|
|
return new self($module, $interface); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @param class-string $class |
|
|
|
|
34
|
|
|
*/ |
35
|
|
|
public function add(string $class, ?string $key = null): void |
36
|
|
|
{ |
37
|
|
|
$this->bind($class, $key); |
38
|
|
|
$bind = (new Bind($this->container, LazyCollection::class))->toInstance(new LazyCollection($this->lazyCollection)); |
39
|
|
|
$this->container->add($bind); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* @param class-string $class |
|
|
|
|
44
|
|
|
*/ |
45
|
|
|
public function set(string $class, ?string $key = null): void |
46
|
|
|
{ |
47
|
|
|
unset($this->lazyCollection[$this->interface]); |
48
|
|
|
$this->add($class, $key); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @param class-string $class |
|
|
|
|
53
|
|
|
*/ |
54
|
|
|
private function bind(string $class, ?string $key): void |
55
|
|
|
{ |
56
|
|
|
if ($key === null) { |
57
|
|
|
$this->lazyCollection[$this->interface][] = new Lazy($class); |
58
|
|
|
|
59
|
|
|
return; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
$this->lazyCollection[$this->interface][$key] = new Lazy($class); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|