Context::get()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 4
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 9
rs 10
1
<?php
2
3
/*
4
 * This file is part of the ICanBoogie package.
5
 *
6
 * (c) Olivier Laviale <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace ICanBoogie\MessageBus;
13
14
/**
15
 * The context in which a message is dispatched.
16
 */
17
final class Context
18
{
19
    /**
20
     * @var object[]
21
     */
22
    private array $objects = [];
23
24
    /**
25
     * @param iterable<object> $objects
26
     */
27
    public function __construct(iterable $objects = [])
28
    {
29
        foreach ($objects as $object) {
30
            $this->add($object);
31
        }
32
    }
33
34
    /**
35
     * Adds an object to the context.
36
     */
37
    public function add(object $object): self
38
    {
39
        array_unshift($this->objects, $object);
40
41
        return $this;
42
    }
43
44
    /**
45
     * Returns the object matching the specified class.
46
     *
47
     * @template T of object
48
     *
49
     * @param class-string<T> $class
50
     *
51
     * @return T
52
     *
53
     * @throws NotInContext
54
     */
55
    public function get(string $class): object
56
    {
57
        foreach ($this->objects as $object) {
58
            if ($object instanceof $class) {
59
                return $object;
60
            }
61
        }
62
63
        throw new NotInContext($class);
64
    }
65
}
66