Completed
Push — master ( 82b030...f3e878 )
by Frank
01:03
created

PrioritizedListenerCollection   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 10
lcom 1
cbo 3
dl 0
loc 50
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
A getListenersForEvent() 0 16 4
A getListenersForEventName() 0 8 2
A subscribeTo() 0 8 2
A subscribeOnceTo() 0 4 1
A subscribeListenersFrom() 0 4 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace League\Event;
6
7
use Psr\EventDispatcher\ListenerProviderInterface;
8
9
class PrioritizedListenerCollection implements ListenerAcceptor, ListenerProviderInterface
10
{
11
    /** @var array<string,PrioritizedListenersForEvent> */
12
    protected $listenersPerEvent = [];
13
14
    public function subscribeTo(string $event, callable $listener, int $priority = self::P_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 = self::P_NORMAL): void
24
    {
25
        $this->subscribeTo($event, new OneTimeListener($listener), $priority);
26
    }
27
28
    public function getListenersForEvent(object $event): iterable
29
    {
30
        if ($event instanceof HasEventName) {
31
            yield from $this->getListenersForEventName($event->eventName());
32
        }
33
34
        /**
35
         * @var string                       $key
36
         * @var PrioritizedListenersForEvent $group
37
         */
38
        foreach ($this->listenersPerEvent as $key => $group) {
39
            if ($event instanceof $key) {
40
                yield from $group->getListeners();
41
            }
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