Events::on()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 2
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Events trait
5
 *
6
 * Add to a class for a generic, private event emitter-listener.
7
 *
8
 * @package core
9
 * @author [email protected]
10
 * @copyright Caffeina srl - 2015-2016 - http://caffeina.com
11
 */
12
13
trait Events {
14
15
    protected static $_listeners = [];
16
17
    public static function on($name,callable $listener){
18
        static::$_listeners[$name][] = $listener;
19
    }
20
21
    public static function onSingle($name,callable $listener){
22
        static::$_listeners[$name] = [$listener];
23
    }
24
25 View Code Duplication
    public static function off($name,callable $listener = null){
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
26
        if($listener === null) {
27
            unset(static::$_listeners[$name]);
28
        } else {
29
            if ($idx = array_search($listener,static::$_listeners[$name],true))
30
                unset(static::$_listeners[$name][$idx]);
31
        }
32
    }
33
34
    public static function alias($source,$alias){
35
        static::$_listeners[$alias] =& static::$_listeners[$source];
36
    }
37
38
    public static function trigger($name, ...$args){
39
        if (false === empty(static::$_listeners[$name])){
40
            $results = [];
41
            foreach (static::$_listeners[$name] as $listener) {
42
                $results[] = $listener(...$args);
43
            }
44
            return $results;
45
        };
46
    }
47
48
    public static function triggerOnce($name){
49
        $res = static::trigger($name);
50
        unset(static::$_listeners[$name]);
51
        return $res;
52
    }
53
54
}
55