Passed
Pull Request — master (#134)
by Dmitriy
11:48
created

CompositeContainer   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Test Coverage

Coverage 90%

Importance

Changes 0
Metric Value
eloc 21
dl 0
loc 64
ccs 18
cts 20
cp 0.9
rs 10
c 0
b 0
f 0
wmc 16

5 Methods

Rating   Name   Duplication   Size   Complexity  
A attach() 0 3 1
A has() 0 8 3
A detach() 0 5 3
A get() 0 14 6
A hasDefinition() 0 8 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Di;
6
7
use Psr\Container\ContainerInterface;
8
use Yiisoft\Factory\Exceptions\NotFoundException;
9
10
/**
11
 * This class implements a composite container for use with containers that support the delegate lookup feature.
12
 * The goal of the implementation is simplicity.
13
 */
14
final class CompositeContainer extends AbstractContainerConfigurator implements ContainerInterface
15
{
16
    /**
17
     * Containers to look into starting from the beginning of the array.
18
     * @var ContainerInterface[] The list of containers
19
     */
20
    private array $containers = [];
21
22 23
    public function get($id)
23
    {
24 23
        foreach ($this->containers as $container) {
25 23
            if (method_exists($container, 'hasDefinition') && $container->hasDefinition($id)) {
26 20
                return $container->get($id);
27
            }
28
        }
29 20
30
        foreach ($this->containers as $container) {
31
            if ($container->has($id)) {
32 5
                return $container->get($id);
33
            }
34
        }
35 8
        throw new NotFoundException("No definition for $id");
36
    }
37 8
38 8
    public function has($id): bool
39 8
    {
40
        foreach ($this->containers as $container) {
41
            if ($container->has($id)) {
42
                return true;
43
            }
44
        }
45
        return false;
46
    }
47
48
    /**
49 25
     * Attaches a container to the composite container.
50
     * @param ContainerInterface $container
51 25
     */
52 25
    public function attach(ContainerInterface $container): void
53
    {
54
        array_unshift($this->containers, $container);
55
    }
56
57
    /**
58 2
     * Removes a container from the list of containers.
59
     * @param ContainerInterface $container
60 2
     */
61 2
    public function detach(ContainerInterface $container): void
62 2
    {
63
        foreach ($this->containers as $i => $c) {
64
            if ($container === $c) {
65 2
                unset($this->containers[$i]);
66
            }
67
        }
68
    }
69
70
    protected function hasDefinition($id): bool
71
    {
72
        foreach ($this->containers as $container) {
73
            if ($container->hasDefinition($id)) {
74
                return true;
75
            }
76
        }
77
        return false;
78
    }
79
}
80