ContainerComposite::getLowestPriority()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 0
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
4
namespace Habemus;
5
6
use Habemus\Exception\NotFoundException;
7
use Habemus\Utility\Lists\ObjectPriorityList;
8
use Psr\Container\ContainerInterface;
9
10
class ContainerComposite implements ContainerInterface
11
{
12
    /**
13
     * @var ObjectPriorityList
14
     */
15
    protected $containers;
16
17
    /**
18
     * Skips array elements that do not implement ContainerInterface (PSR-11)
19
     * @param array $containers Containers indexed by priority
20
     */
21
    public function __construct(array $containers = [])
22
    {
23
        $this->containers = new ObjectPriorityList();
24
        foreach ($containers as $priority => $container) {
25
            if ($container instanceof ContainerInterface) {
26
                $this->add($container, (int) $priority);
27
            }
28
        }
29
    }
30
31
    /**
32
     * If priority is empty, appends with the lowest priority
33
     * @param ContainerInterface $container
34
     * @param int|null $priority
35
     * @return $this
36
     */
37
    public function add(ContainerInterface $container, ?int $priority = null): self
38
    {
39
        if (!is_int($priority)) {
40
            $priority = $this->getLowestPriority() + 1;
41
        }
42
43
        $this->containers->add($container, $priority);
44
        return $this;
45
    }
46
47
    /**
48
     * @inheritDoc
49
     */
50
    public function has($id): bool
51
    {
52
        foreach ($this->containers as $container) {
53
            if ($container->has($id)) {
54
                return true;
55
            }
56
        }
57
58
        return false;
59
    }
60
61
    /**
62
     * @inheritDoc
63
     */
64
    public function get($id)
65
    {
66
        foreach ($this->containers as $container) {
67
            if ($container->has($id)) {
68
                return $container->get($id);
69
            }
70
        }
71
72
        throw NotFoundException::noEntryWasFound($id);
73
    }
74
75
    public function getLowestPriority(): int
76
    {
77
        return (int) $this->containers->getLowestPriority();
78
    }
79
80
    public function getHighestPriority(): int
81
    {
82
        return (int) $this->containers->getHighestPriority();
83
    }
84
}
85