Completed
Push — master ( 71fe6c...2dd80e )
by Koldo
02:32
created

Container::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 2.0116

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 6
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 8
ccs 6
cts 7
cp 0.8571
crap 2.0116
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Antidot\Container;
6
7
use Psr\Container\ContainerInterface;
8
9
class Container implements ContainerInterface
10
{
11
    private $autowire;
12
    private $loadedDependencies;
13
    private $configuredDependencies;
14
    /** @var InstanceResolver */
15
    private $resolver;
16
17 13
    public function __construct(ContainerConfig $configuredDependencies, bool $autowire)
18
    {
19 13
        $this->configuredDependencies = $configuredDependencies->has('delegators')
20
            ? (new MarshalDelegatorsConfig())($this, $configuredDependencies)
21 13
            : $configuredDependencies;
22 13
        $this->loadedDependencies = new InstanceCollection();
23 13
        $this->loadedDependencies->set('config', $configuredDependencies->get('config'));
24 13
        $this->autowire = $autowire;
25 13
    }
26
27 12
    public function get($id)
28
    {
29 12
        if ($this->loadedDependencies->has($id)) {
30 4
            return $this->loadedDependencies->get($id);
31
        }
32
33 11
        if ($this->autowire) {
34 9
            $this->setInstanceResolver();
35 9
            $this->resolver->setInstanceOf($id);
36 8
            return $this->loadedDependencies->get($id);
37
        }
38
39 2
        $this->loadedDependencies->set($id, $this->getService($id));
40
41 1
        return $this->loadedDependencies->get($id);
42
    }
43
44 6
    public function has($id): bool
45
    {
46 6
        return $this->loadedDependencies->has($id)
47 6
            || $this->configuredDependencies->has($id);
48
    }
49
50 2
    private function getService(string $id)
51
    {
52 2
        if (is_callable($this->configuredDependencies->get($id))) {
53 1
            $callableService = $this->configuredDependencies->get($id);
54 1
            return $callableService($this);
55
        }
56
57 2
        if (is_object($this->configuredDependencies->get($id))) {
58 1
            return $this->configuredDependencies->get($id);
59
        }
60
61 1
        throw ServiceNotFoundException::forId($id);
62
    }
63
64 9
    private function setInstanceResolver(): void
65
    {
66 9
        if (null === $this->resolver) {
67 9
            $this->resolver = new InstanceResolver($this->configuredDependencies, $this->loadedDependencies, $this);
68
        }
69 9
    }
70
}
71