Passed
Push — master ( 25ca8a...f7ffed )
by Alexander
02:24 queued 42s
created

CompositeContainer::attach()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 0
b 0
f 0
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 25
    public function get($id)
23
    {
24 25
        foreach ($this->containers as $container) {
25 25
            if ($container->has($id)) {
26 22
                return $container->get($id);
27
            }
28
        }
29 5
        throw new NotFoundException("No definition for $id");
30
    }
31
32 9
    public function has($id): bool
33
    {
34 9
        foreach ($this->containers as $container) {
35 9
            if ($container->has($id)) {
36 9
                return true;
37
            }
38
        }
39
        return false;
40
    }
41
42
    /**
43
     * Attaches a container to the composite container.
44
     * @param ContainerInterface $container
45
     */
46 27
    public function attach(ContainerInterface $container): void
47
    {
48 27
        array_unshift($this->containers, $container);
49 27
    }
50
51
    /**
52
     * Removes a container from the list of containers.
53
     * @param ContainerInterface $container
54
     */
55 2
    public function detach(ContainerInterface $container): void
56
    {
57 2
        foreach ($this->containers as $i => $c) {
58 2
            if ($container === $c) {
59 2
                unset($this->containers[$i]);
60
            }
61
        }
62 2
    }
63
}
64