Completed
Push — develop ( c0cf48...9f68ce )
by Baptiste
03:11
created

Dependencies::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 6
nc 1
nop 1
dl 0
loc 8
ccs 7
cts 7
cp 1
crap 1
rs 9.4285
c 0
b 0
f 0
1
<?php
2
declare(strict_types = 1);
3
4
namespace Innmind\Compose;
5
6
use Innmind\Compose\{
7
    Definition\Dependency,
8
    Definition\Name,
9
    Exception\ReferenceNotFound,
10
    Exception\NameNotNamespaced
11
};
12
use Innmind\Immutable\{
13
    Sequence,
14
    Map
15
};
16
17
final class Dependencies
18
{
19
    private $dependencies;
20
21 5
    public function __construct(Dependency ...$dependencies)
22
    {
23 5
        $this->dependencies = Sequence::of(...$dependencies)->reduce(
24 5
            new Map('string', Dependency::class),
25 5
            static function(Map $dependencies, Dependency $dependency): Map {
26 5
                return $dependencies->put(
27 5
                    (string) $dependency->name(),
28 5
                    $dependency
29
                );
30 5
            }
31
        );
32
        // todo: ensure no circular dependency when cross dependency argument supported
33 5
    }
34
35 1
    public function bind(Services $services): self
36
    {
37 1
        $self = clone $this;
38 1
        $self->dependencies = $self
39 1
            ->dependencies
40 1
            ->map(static function(string $name, Dependency $dependency) use ($services): Dependency {
41 1
                return $dependency->bind($services);
42 1
            });
43
44 1
        return $self;
45
    }
46
47 5
    public function build(Name $name): object
48
    {
49
        try {
50 5
            $root = $name->root();
51 1
        } catch (NameNotNamespaced $e) {
52 1
            throw new ReferenceNotFound((string) $name);
53
        }
54
55 4
        if (!$this->dependencies->contains((string) $root)) {
56 1
            throw new ReferenceNotFound((string) $name);
57
        }
58
59
        try {
60
            return $this
61 3
                ->dependencies
62 3
                ->get((string) $root)
63 3
                ->build($name->withoutRoot());
64 2
        } catch (ReferenceNotFound $e) {
65 1
            throw new ReferenceNotFound((string) $name, 0, $e);
66
        }
67
    }
68
}
69