Completed
Push — master ( d18e7c...c1c328 )
by Maxim
02:45
created

TraitObservable::trigger()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 2
1
<?php
2
3
namespace WebComplete\core\utils\traits;
4
5
trait TraitObservable
6
{
7
8
    private $listeners = [];
9
10
    /**
11
     * @param string $eventName
12
     * @param array $eventData
13
     */
14
    public function trigger(string $eventName, array $eventData)
15
    {
16
        $listeners = $this->listeners[$eventName] ?? [];
17
        foreach ($listeners as $listener) {
18
            \call_user_func($listener[1], $eventData);
19
        }
20
    }
21
22
    /**
23
     * @param string $eventName
24
     * @param callable $callable
25
     * @param int $priority
26
     */
27
    public function on(string $eventName, callable $callable, int $priority = 100)
28
    {
29
        if (!isset($this->listeners[$eventName])) {
30
            $this->listeners[$eventName] = [];
31
        }
32
33
        $this->listeners[$eventName][] = [$priority, $callable];
34
        \uasort($this->listeners[$eventName], function ($event1, $event2) {
35
            return $event1[0] <=> $event2[0];
36
        });
37
    }
38
39
    /**
40
     * @return array
41
     */
42
    public function getListeners(): array
43
    {
44
        return $this->listeners;
45
    }
46
47
    /**
48
     * @param array $listeners
49
     */
50
    public function setListeners(array $listeners)
51
    {
52
        $this->listeners = $listeners;
53
    }
54
}
55