Passed
Push — master ( a6aefd...a6f236 )
by mahdi
02:46
created

EventEmitter::__call()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 1 Features 0
Metric Value
cc 1
eloc 1
c 1
b 1
f 0
nc 1
nop 2
dl 0
loc 3
rs 10
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
            if (empty($listener)) { // remove the event and all of its listeners
46
                unset($this->listeners[$event]);
47
            } else {  // remove only the given listener if exists
48
                $listenerIndex = array_search($listener, $this->listeners[$event]);
49
50
                if ($listenerIndex !== false) {
51
                    unset($this->listeners[$event][$listenerIndex]);
52
                }
53
            }
54
        }
55
    }
56
57
    /**
58
     * Run event listeners.
59
     *
60
     * @param string $event
61
     * @param array ...$arguments
62
     *
63
     * @return void
64
     */
65
    public function dispatch(string $event, ...$arguments)
66
    {
67
        $listeners = $this->listeners;
68
69
        if (empty($listeners[$event])) {
70
            return;
71
        }
72
73
        array_walk($listeners[$event], function ($listener) use ($arguments) {
74
            call_user_func_array($listener, $arguments);
75
        });
76
    }
77
78
    /**
79
     * Call events by their name.
80
     *
81
     * @param string $name
82
     * @param array $arguments
83
     *
84
     * @return void
85
     */
86
    public function __call($name, $arguments)
87
    {
88
        $this->dispatch($name, $arguments);
89
    }
90
}
91