Passed
Pull Request — master (#5)
by Olivier
01:46
created

Context::__construct()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 2
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 4
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
use LogicException;
15
16
/**
17
 * The context in which a message is dispatched.
18
 */
19
final class Context
20
{
21
    /**
22
     * @var object[]
23
     */
24
    private array $objects = [];
25
26
    /**
27
     * @param iterable<object> $objects
28
     */
29
    public function __construct(iterable $objects = [])
30
    {
31
        foreach ($objects as $object) {
32
            $this->add($object);
33
        }
34
    }
35
36
    /**
37
     * Adds an object to the context.
38
     */
39
    public function add(object $object): self
40
    {
41
        array_unshift($this->objects, $object);
42
43
        return $this;
44
    }
45
46
    /**
47
     * Returns the object matching the specified class.
48
     *
49
     * @template T of object
50
     *
51
     * @param class-string<T> $class
1 ignored issue
show
Documentation Bug introduced by
The doc comment class-string<T> at position 0 could not be parsed: Unknown type name 'class-string' at position 0 in class-string<T>.
Loading history...
52
     *
53
     * @return T
54
     *
55
     * @throws NotInContext
56
     */
57
    public function get(string $class): object
58
    {
59
        foreach ($this->objects as $object) {
60
            if ($object instanceof $class) {
61
                return $object;
62
            }
63
        }
64
65
        throw new NotInContext($class);
66
    }
67
}
68