Container::getService()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 6
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 12
ccs 7
cts 7
cp 1
crap 3
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 bool $autowire;
12
    private InstanceCollection $loadedDependencies;
13
    private ContainerConfig $configuredDependencies;
14
    private InstanceResolver $resolver;
15
16 21
    public function __construct(ContainerConfig $configuredDependencies, bool $autowire)
17
    {
18 21
        $this->configuredDependencies = $configuredDependencies->has('delegators')
19 15
            ? (new MarshalDelegatorsConfig())($configuredDependencies)
20 6
            : $configuredDependencies;
21 21
        $this->loadedDependencies = new InstanceCollection();
22 21
        $this->loadedDependencies->set('config', $configuredDependencies->get('config'));
23 21
        $this->autowire = $autowire;
24 21
        $this->resolver = new InstanceResolver($this->configuredDependencies, $this->loadedDependencies, $this);
25 21
    }
26
27 19
    public function get($id)
28
    {
29 19
        if ($this->loadedDependencies->has($id)) {
30 4
            return $this->loadedDependencies->get($id);
31
        }
32
33 18
        if ($this->autowire) {
34 16
            $this->resolver->setInstanceOf($id);
35 15
            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 10
    public function has($id): bool
44
    {
45 10
        return $this->loadedDependencies->has($id)
46 10
            || $this->configuredDependencies->has($id);
47
    }
48
49 2
    private function getService(string $id): object
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