Passed
Push — multi_binding ( 2522c7...aaa0d4 )
by Akihito
02:03
created

MultiBinder::bind()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
c 0
b 0
f 0
dl 0
loc 9
rs 10
cc 2
nc 2
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Ray\Di\MultiBinding;
6
7
use Ray\Di\AbstractModule;
8
use Ray\Di\Bind;
9
use Ray\Di\Container;
10
11
final class MultiBinder
12
{
13
    /** @var Container */
14
    private $container;
15
16
    /** @var array<string, array<int|string, Lazy>> */
17
    private $lazyCollection = [];
18
19
    /** @var string */
20
    private $interface;
21
22
    private function __construct(AbstractModule $module, string $interface)
23
    {
24
        $this->container = $module->getContainer();
25
        $this->interface = $interface;
26
    }
27
28
    public static function newInstance(AbstractModule $module, string $interface): self
29
    {
30
        return new self($module, $interface);
31
    }
32
33
    /**
34
     * @param class-string $class
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string.
Loading history...
35
     */
36
    public function add(string $class, ?string $key = null): void
37
    {
38
        $this->bind($class, $key);
39
        $bind = (new Bind($this->container, LazyCollection::class))->toInstance(new LazyCollection($this->lazyCollection));
40
        $this->container->add($bind);
41
    }
42
43
    public function set(string $class, ?string $key = null): void
44
    {
45
        unset($this->lazyCollection[$this->interface]);
46
        $this->add($class, $key);
47
    }
48
49
    /**
50
     * @param class-string $class
0 ignored issues
show
Documentation Bug introduced by
The doc comment class-string at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string.
Loading history...
51
     */
52
    private function bind(string $class, ?string $key): void
53
    {
54
        if ($key === null) {
55
            $this->lazyCollection[$this->interface][] = new Lazy($class);
56
57
            return;
58
        }
59
60
        $this->lazyCollection[$this->interface][$key] = new Lazy($class);
61
    }
62
}
63