Passed
Push — master ( 2f1ba5...cc479d )
by Koldo
04:20
created

Container::setInstanceResolver()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 0
dl 0
loc 4
ccs 3
cts 3
cp 1
crap 2
rs 10
c 0
b 0
f 0
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 bool $autowire;
12
    private InstanceCollection $loadedDependencies;
13
    private ContainerConfig $configuredDependencies;
14
    private InstanceResolver $resolver;
15
16 14
    public function __construct(ContainerConfig $configuredDependencies, bool $autowire)
17
    {
18 14
        $this->configuredDependencies = $configuredDependencies->has('delegators')
19 8
            ? (new MarshalDelegatorsConfig())($configuredDependencies)
20 6
            : $configuredDependencies;
21 14
        $this->loadedDependencies = new InstanceCollection();
22 14
        $this->loadedDependencies->set('config', $configuredDependencies->get('config'));
23 14
        $this->autowire = $autowire;
24 14
        $this->resolver = new InstanceResolver($this->configuredDependencies, $this->loadedDependencies, $this);
25 14
    }
26
27 13
    public function get($id)
28
    {
29 13
        if ($this->loadedDependencies->has($id)) {
30 4
            return $this->loadedDependencies->get($id);
31
        }
32
33 12
        if ($this->autowire) {
34 10
            $this->resolver->setInstanceOf($id);
35 9
            return $this->loadedDependencies->get($id);
36
        }
37
38 2
        $this->loadedDependencies->set($id, $this->getService($id));
39
40 1
        return $this->loadedDependencies->get($id);
41
    }
42
43 7
    public function has($id): bool
44
    {
45 7
        return $this->loadedDependencies->has($id)
46 7
            || $this->configuredDependencies->has($id);
47
    }
48
49 2
    private function getService(string $id)
50
    {
51 2
        if (is_callable($this->configuredDependencies->get($id))) {
52 1
            $callableService = $this->configuredDependencies->get($id);
53 1
            return $callableService($this);
54
        }
55
56 2
        if (is_object($this->configuredDependencies->get($id))) {
57 1
            return $this->configuredDependencies->get($id);
58
        }
59
60 1
        throw ServiceNotFoundException::forId($id);
61
    }
62
}
63