Passed
Push — github-actions ( e63dce )
by Alexander
03:10
created

CompositeContainer   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 49
Duplicated Lines 0 %

Test Coverage

Coverage 89.47%

Importance

Changes 0
Metric Value
wmc 11
eloc 16
c 0
b 0
f 0
dl 0
loc 49
ccs 17
cts 19
cp 0.8947
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A detach() 0 5 3
A attach() 0 3 1
A has() 0 8 3
A get() 0 11 4
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 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, array $parameters = [])
23
    {
24 23
        foreach ($this->containers as $container) {
25 23
            if ($container->has($id)) {
26 20
                if ($parameters !== []) {
27
                    return $container->get($id, $parameters);
28
                }
29 20
                return $container->get($id);
30
            }
31
        }
32 5
        throw new NotFoundException("No definition for $id");
33
    }
34
35 8
    public function has($id): bool
36
    {
37 8
        foreach ($this->containers as $container) {
38 8
            if ($container->has($id)) {
39 8
                return true;
40
            }
41
        }
42
        return false;
43
    }
44
45
    /**
46
     * Attaches a container to the composite container.
47
     * @param ContainerInterface $container
48
     */
49 25
    public function attach(ContainerInterface $container): void
50
    {
51 25
        array_unshift($this->containers, $container);
52 25
    }
53
54
    /**
55
     * Removes a container from the list of containers.
56
     * @param ContainerInterface $container
57
     */
58 2
    public function detach(ContainerInterface $container): void
59
    {
60 2
        foreach ($this->containers as $i => $c) {
61 2
            if ($container === $c) {
62 2
                unset($this->containers[$i]);
63
            }
64
        }
65 2
    }
66
}
67