TraitObservable   A
last analyzed

Complexity

Total Complexity 7

Size/Duplication

Total Lines 50
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 7
dl 0
loc 50
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A setListeners() 0 3 1
A on() 0 9 2
A getListeners() 0 3 1
A trigger() 0 6 3
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
        if ($this->listeners) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->listeners of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
17
            $listeners = $this->listeners[$eventName] ?? [];
18
            foreach ($listeners as $listener) {
19
                \call_user_func($listener[1], $eventData);
20
            }
21
        }
22
    }
23
24
    /**
25
     * @param string $eventName
26
     * @param callable $callable
27
     * @param int $priority
28
     */
29
    public function on(string $eventName, callable $callable, int $priority = 100)
30
    {
31
        if (!isset($this->listeners[$eventName])) {
32
            $this->listeners[$eventName] = [];
33
        }
34
35
        $this->listeners[$eventName][] = [$priority, $callable];
36
        \uasort($this->listeners[$eventName], function ($event1, $event2) {
37
            return $event1[0] <=> $event2[0];
38
        });
39
    }
40
41
    /**
42
     * @return array
43
     */
44
    public function getListeners(): array
45
    {
46
        return $this->listeners;
47
    }
48
49
    /**
50
     * @param array $listeners
51
     */
52
    public function setListeners(array $listeners)
53
    {
54
        $this->listeners = $listeners;
55
    }
56
}
57