Completed
Push — 2.x ( 5c5bb8...ae2cb5 )
by Akihito
20s queued 13s
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;
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>>> */
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<string, array<int|string, Lazy<object>>> at position 10 could not be parsed: Expected '>' at position 10, but found 'Lazy'.
Loading history...
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
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...
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
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...
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
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...
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