Passed
Pull Request — master (#14)
by Romain
01:20
created

ConcreteProvider::detach()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
c 1
b 0
f 0
1
<?php
2
3
namespace Yiisoft\EventDispatcher\Provider;
4
5
use Psr\EventDispatcher\ListenerProviderInterface;
6
7
use function array_values;
8
use function class_implements;
9
use function class_parents;
10
use function get_class;
11
12
final class ConcreteProvider implements ListenerProviderInterface
13
{
14
    /**
15
     * @var callable[]
16
     */
17
    private array $listeners = [];
18
19
    /**
20
     * @param object $event
21
     * @return iterable<callable>
22
     */
23 9
    public function getListenersForEvent(object $event): iterable
24
    {
25 9
        yield from $this->listenersFor(get_class($event));
26 8
        yield from $this->listenersFor(...array_values(class_parents($event)));
27 8
        yield from $this->listenersFor(...array_values(class_implements($event)));
28
    }
29
30
    /**
31
     * Attach an event handler for the given event name
32
     *
33
     * @param string $eventName
34
     * @param callable $listener
35
     */
36 9
    public function attach(string $eventName, callable $listener): void
37
    {
38 9
        $this->listeners[$eventName][] = $listener;
39
    }
40
41
    /**
42
     * Detach all event handlers registered for an interface
43
     *
44
     * @param string $interface
45
     */
46 1
    public function detach(string $interface): void
47
    {
48 1
        unset($this->listeners[$interface]);
49
    }
50
51
    /**
52
     * @param string ...$eventNames
53
     * @return iterable<callable>
54
     */
55 9
    private function listenersFor(string ...$eventNames): iterable
56
    {
57 9
        foreach ($eventNames as $name) {
58 9
            if (isset($this->listeners[$name])) {
59 8
                yield from $this->listeners[$name];
60
            }
61
        }
62
    }
63
}
64