Completed
Push — master ( fadeb4...d2fa33 )
by Alexander
02:05
created

CompositeContainer::has()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
cc 3
eloc 4
nc 3
nop 1
dl 0
loc 8
ccs 0
cts 8
cp 0
crap 12
rs 10
c 0
b 0
f 0
1
<?php
2
namespace Yiisoft\Di;
3
4
use Psr\Container\ContainerInterface;
5
use Psr\Container\NotFoundExceptionInterface;
6
use Yiisoft\Factory\Exceptions\NotFoundException;
7
8
/**
9
 * This class implements a composite container for use with containers that support the delegate lookup feature.
10
 * The goal of the implementation is simplicity.
11
 */
12
class CompositeContainer implements ContainerInterface
13
{
14
    /**
15
     * Containers to look into starting from the beginning of the array.
16
     * @var ContainerInterface[] The list of containers
17
     */
18
    private $containers = [];
19
20
    public function get($id)
21
    {
22
        foreach ($this->containers as $container) {
23
            try {
24
                return $container->get($id);
25
            } catch (NotFoundExceptionInterface $e) {
26
                // ignore
27
            }
28
        }
29
        throw new NotFoundException("No definition for $id");
30
    }
31
32
    public function has($id)
33
    {
34
        foreach ($this->containers as $container) {
35
            if ($container->has($id)) {
36
                return true;
37
            }
38
        }
39
        return false;
40
    }
41
42
    /**
43
     * Attaches a container to the composite container.
44
     * @param ContainerInterface $container
45
     */
46
    public function attach(ContainerInterface $container): void
47
    {
48
        array_unshift($this->containers, $container);
49
    }
50
51
    /**
52
     * Removes a container from the list of containers.
53
     * @param ContainerInterface $container
54
     */
55
    public function detach(ContainerInterface $container): void
56
    {
57
        foreach ($this->containers as $i => $c) {
58
            if ($container === $c) {
59
                unset($this->containers[$i]);
60
            }
61
        }
62
    }
63
}
64