EventEmitter::removeEventListener()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 8
nc 4
nop 2
dl 0
loc 18
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Shetabit\Multipay;
4
5
class EventEmitter
6
{
7
    /**
8
     * List of listeners.
9
     *
10
     * @description a pair of $event => [array of listeners]
11
     *
12
     * @var array
13
     */
14
    private $listeners = [];
15
16
    /**
17
     * Add new listener fo given event.
18
     *
19
     * @param string $event
20
     * @param callable $listener
21
     *
22
     * @return void
23
     */
24
    public function addEventListener(string $event, callable $listener)
25
    {
26
        if (empty($this->listeners[$event]) || !is_array($this->listeners[$event])) {
27
            $this->listeners[$event] = [];
28
        }
29
30
        array_push($this->listeners[$event], $listener);
31
    }
32
33
    /**
34
     * Remove given listener from a specefic event.
35
     * if we call this method without listener, it will totaly remove the given event and all of its listeners.
36
     *
37
     * @param string $event
38
     * @param callable $listener
39
     *
40
     * @return void
41
     */
42
    public function removeEventListener(string $event, callable $listener = null)
43
    {
44
        if (empty($this->listeners[$event])) {
45
            return;
46
        }
47
48
        // remove the event and all of its listeners
49
        if (empty($listener)) {
50
            unset($this->listeners[$event]);
51
52
            return;
53
        }
54
55
        // remove only the given listener if exists
56
        $listenerIndex = array_search($listener, $this->listeners[$event]);
57
58
        if ($listenerIndex !== false) {
59
            unset($this->listeners[$event][$listenerIndex]);
60
        }
61
    }
62
63
    /**
64
     * Run event listeners.
65
     *
66
     * @param string $event
67
     * @param array ...$arguments
68
     *
69
     * @return void
70
     */
71
    public function dispatch(string $event, ...$arguments)
72
    {
73
        $listeners = $this->listeners;
74
75
        if (empty($listeners[$event])) {
76
            return;
77
        }
78
79
        array_walk($listeners[$event], function ($listener) use ($arguments) {
80
            call_user_func_array($listener, $arguments);
81
        });
82
    }
83
84
    /**
85
     * Call events by their name.
86
     *
87
     * @param string $name
88
     * @param array $arguments
89
     *
90
     * @return void
91
     */
92
    public function __call($name, $arguments)
93
    {
94
        $this->dispatch($name, $arguments);
95
    }
96
}
97