Completed
Push — master ( 703642...46fb8b )
by Daniel
02:13
created

SimpleEmitter::getEventListeners()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 5
rs 9.4285
cc 2
eloc 3
nc 2
nop 1
1
<?php
2
/**
3
 * @package event
4
 */
5
6
7
namespace Mleko\Event;
8
9
10
class SimpleEmitter implements MutableEmitter
11
{
12
13
    /** @var array */
14
    private $listeners = [];
15
16
    /** @var EventNameExtractor */
17
    private $eventNameExtractor;
18
19
    /**
20
     * SimpleEventBus constructor.
21
     * @param EventNameExtractor $eventNameExtractor
22
     */
23
    public function __construct(EventNameExtractor $eventNameExtractor)
24
    {
25
        $this->eventNameExtractor = $eventNameExtractor;
26
    }
27
28
    /**
29
     * @param object $event
30
     * @return void
31
     */
32
    public function emit($event)
33
    {
34
        $eventName = $this->extractEventName($event);
35
        $eventListeners = $this->getEventListeners($eventName);
36
        foreach ($eventListeners as $listener) {
37
            $listener->handle($event);
38
        }
39
    }
40
41
    /**
42
     * @param string $eventName
43
     * @param Listener $listener
44
     * @return Subscription
45
     */
46
    public function addListener($eventName, Listener $listener)
47
    {
48
        $this->listeners[$eventName][] = $listener;
49
        return new Subscription($eventName, $listener, $this);
50
    }
51
52
    /**
53
     * @param string $eventName
54
     * @param Listener $listener
55
     * @return bool
56
     */
57
    public function removeListener($eventName, Listener $listener)
58
    {
59
        $eventListeners = $this->getEventListeners($eventName);
60
        foreach ($eventListeners as $key => $eventListener) {
61
            if ($listener === $eventListener) {
62
                unset($this->listeners[$eventName][$key]);
63
                return true;
64
            }
65
        }
66
        return false;
67
    }
68
69
    /**
70
     * @param $event
71
     * @return string
72
     */
73
    private function extractEventName($event)
74
    {
75
        return $this->eventNameExtractor->extract($event);
76
    }
77
78
    /**
79
     * @param $eventName
80
     * @return Listener[]
81
     */
82
    private function getEventListeners($eventName)
83
    {
84
        $eventListeners = array_key_exists($eventName, $this->listeners) ? $this->listeners[$eventName] : [];
85
        return $eventListeners;
86
    }
87
}
88