Completed
Push — sam-rework ( 1696e6 )
by Andrii
38:13 queued 23:11
created

CompositeContainer::detach()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 3
nc 3
nop 1
1
<?php
2
3
4
namespace yii\di;
5
6
use Psr\Container\ContainerInterface;
7
use Psr\Container\NotFoundExceptionInterface;
8
use yii\di\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
 * Class CompositeContainer
14
 * @package yii\di
15
 */
16
class CompositeContainer implements ContainerInterface
17
{
18
    /**
19
     * We use a simple array since order matters
20
     * @var ContainerInterface[] The list of containers
21
     */
22
    private $containers = [];
23
24
    /** @inheritdoc */
25
    public function get($id)
26
    {
27
        foreach ($this->containers as $container) {
28
            try {
29
                return $container->get($id);
30
            } catch (NotFoundExceptionInterface $e) {
31
                continue;
32
            }
33
        }
34
        throw new NotFoundException();
35
    }
36
37
    /** @inheritdoc */
38
    public function has($id)
39
    {
40
        foreach ($this->containers as $container) {
41
            if ($container->has($id)) {
42
                return true;
43
            }
44
        }
45
        return false;
46
    }
47
48
    /**
49
     * Attaches a container to the composite container.
50
     * @param ContainerInterface $container
51
     */
52
    public function attach(ContainerInterface $container)
53
    {
54
        array_unshift($this->containers, $container);
55
    }
56
57
    /**
58
     * Removes a container from the list of containers.
59
     * @param ContainerInterface $container
60
     */
61
    public function detach(ContainerInterface $container)
62
    {
63
        foreach ($this->containers as $i => $c) {
64
            if ($container === $c) {
65
                unset($this->containers[$i]);
66
            }
67
        }
68
        $this->containers = array_values($this->containers);
69
    }
70
}
71