Completed
Push — master ( 5ffcc1...94ed56 )
by Miloš
01:45
created

ContainerBuilder::addDefinitions()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 1
dl 0
loc 10
ccs 6
cts 6
cp 1
crap 3
rs 9.9332
c 0
b 0
f 0
1
<?php
2
3
namespace Laganica\Di;
4
5
use ArrayObject;
6
use Laganica\Di\Definition\DefinitionFactory;
7
use Laganica\Di\Exception\ContainerException;
8
use Laganica\Di\Resolver\ResolverFactory;
9
10
/**
11
 * Class ContainerBuilder
12
 *
13
 * @package Laganica\Di
14
 */
15
class ContainerBuilder
16
{
17
    /**
18
     * @var ArrayObject
19
     */
20
    private $definitions;
21
22
    /**
23
     * @var bool
24
     */
25
    private $autowire;
26
27 19
    public function __construct()
28
    {
29 19
        $this->init();
30 19
    }
31
32
    /**
33
     * @param bool $autowire
34
     */
35 19
    public function setAutowire(bool $autowire): void
36
    {
37 19
        $this->autowire = $autowire;
38 19
    }
39
40
    /**
41
     * @return bool
42
     */
43 18
    private function isAutowire(): bool
44
    {
45 18
        return $this->autowire;
46
    }
47
48
    /**
49
     * @param array $definitions
50
     *
51
     * @throws ContainerException
52
     */
53 14
    public function addDefinitions(array $definitions): void
54
    {
55 14
        foreach ($definitions as $id => $definition) {
56 14
            if ($this->definitions->offsetExists($id)) {
57 1
                throw new ContainerException("More than one definition is found for entry or class $id");
58
            }
59
60 14
            $this->definitions->offsetSet($id, $definition);
61
        }
62 14
    }
63
64
    /**
65
     * @return ArrayObject
66
     */
67 18
    private function getDefinitions(): ArrayObject
68
    {
69 18
        return $this->definitions;
70
    }
71
72
    /**
73
     * @return Container
74
     */
75 18
    public function build(): Container
76
    {
77 18
        $container = new Container(new DefinitionFactory(), new ResolverFactory());
78 18
        $container->setAutowire($this->isAutowire());
79 18
        $container->setDefinitions($this->getDefinitions());
80 18
        $this->init();
81
82 18
        return $container;
83
    }
84
85
    /**
86
     * @return void
87
     */
88 19
    private function init(): void
89
    {
90 19
        $this->setAutowire(true);
91 19
        $this->definitions = new ArrayObject();
92 19
    }
93
}
94