ListenerProviderChain   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 45
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 7
c 1
b 0
f 0
dl 0
loc 45
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A appendListenerProviders() 0 3 1
A prependListenerProviders() 0 3 1
A getListenersForEvent() 0 5 3
1
<?php
2
3
/*
4
 * (c) Olivier Laviale <[email protected]>
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
namespace olvlvl\EventDispatcher;
11
12
use Psr\EventDispatcher\ListenerProviderInterface;
13
14
use function array_push;
15
use function array_unshift;
16
17
/**
18
 * A chain of Listener Providers.
19
 *
20
 * Listener Providers are called in succession to provide Listeners for an Event.
21
 */
22
final class ListenerProviderChain implements ListenerProviderInterface
23
{
24
    /**
25
     * @var ListenerProviderInterface[]
26
     */
27
    private $providers = [];
28
29
    /**
30
     * @param ListenerProviderInterface[] $providers
31
     */
32
    public function __construct(iterable $providers = [])
33
    {
34
        $this->appendListenerProviders(...$providers);
35
    }
36
37
    /**
38
     * Add Listener Providers to the end of the chain.
39
     *
40
     * Note: Listener Providers are appended to the chain just like `array_push` append values to an array.
41
     */
42
    public function appendListenerProviders(ListenerProviderInterface ...$providers): void
43
    {
44
        array_push($this->providers, ...$providers);
45
    }
46
47
    /**
48
     * Add Listener Providers to the beginning of the chain.
49
     *
50
     * Note: Listener Providers are prepended to the chain just like `array_unshift` prepend values to an array.
51
     */
52
    public function prependListenerProviders(ListenerProviderInterface ...$providers): void
53
    {
54
        array_unshift($this->providers, ...$providers);
55
    }
56
57
    /**
58
     * @inheritDoc
59
     *
60
     * @return iterable<callable(object):void>
61
     */
62
    public function getListenersForEvent(object $event): iterable
63
    {
64
        foreach ($this->providers as $provider) {
65
            foreach ($provider->getListenersForEvent($event) as $listener) {
66
                yield $listener;
67
            }
68
        }
69
    }
70
}
71