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

PrioritizedListenerCollection::subscribeOnceTo()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 3
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