Completed
Push — master ( e5bccd...d38106 )
by Frank
01:10
created

getListenersForEventName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 8
rs 10
c 0
b 0
f 0
cc 2
nc 2
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace League\Event;
6
7
use Psr\EventDispatcher\ListenerProviderInterface;
8
9
class PrioritizedListenerRegistry implements ListenerRegistry, ListenerProviderInterface
10
{
11
    /** @var array<string,PrioritizedListenersForEvent> */
12
    protected $listenersPerEvent = [];
13
14
    public function subscribeTo(string $event, callable $listener, int $priority = ListenerPriority::NORMAL): void
15
    {
16
        $group = array_key_exists($event, $this->listenersPerEvent)
17
            ? $this->listenersPerEvent[$event]
18
            : $this->listenersPerEvent[$event] = new PrioritizedListenersForEvent();
19
20
        $group->addListener($listener, $priority);
21
    }
22
23
    public function subscribeOnceTo(string $event, callable $listener, int $priority = ListenerPriority::NORMAL): void
24
    {
25
        $this->subscribeTo($event, new OneTimeListener($listener), $priority);
26
    }
27
28
    public function getListenersForEvent(object $event): iterable
29
    {
30
        /**
31
         * @var string                       $key
32
         * @var PrioritizedListenersForEvent $group
33
         */
34
        foreach ($this->listenersPerEvent as $key => $group) {
35
            if ($event instanceof $key) {
36
                yield from $group->getListeners();
37
            }
38
        }
39
40
        if ($event instanceof HasEventName) {
41
            yield from $this->getListenersForEventName($event->eventName());
42
        }
43
    }
44
45
    private function getListenersForEventName(string $eventName): iterable
46
    {
47
        if ( ! array_key_exists($eventName, $this->listenersPerEvent)) {
48
            return [];
49
        }
50
51
        return $this->listenersPerEvent[$eventName]->getListeners();
52
    }
53
54
    public function subscribeListenersFrom(ListenerSubscriber $subscriber): void
55
    {
56
        $subscriber->subscribeListeners($this);
57
    }
58
}
59