Completed
Push — master ( b0867d...8ab030 )
by Alexander
24s queued 11s
created

CompositeContainer::get()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 10
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
     * Containers to look into starting from the beginning of the array.
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
                // ignore
32
            }
33
        }
34
        throw new NotFoundException("No definition for $id");
35
    }
36
37
    public function has($id)
38
    {
39
        foreach ($this->containers as $container) {
40
            if ($container->has($id)) {
41
                return true;
42
            }
43
        }
44
        return false;
45
    }
46
47
    /**
48
     * Attaches a container to the composite container.
49
     * @param ContainerInterface $container
50
     */
51
    public function attach(ContainerInterface $container): void
52
    {
53
        array_unshift($this->containers, $container);
54
    }
55
56
    /**
57
     * Removes a container from the list of containers.
58
     * @param ContainerInterface $container
59
     */
60
    public function detach(ContainerInterface $container): void
61
    {
62
        foreach ($this->containers as $i => $c) {
63
            if ($container === $c) {
64
                unset($this->containers[$i]);
65
            }
66
        }
67
    }
68
}
69