Completed
Push — master ( 05e8ae...5c8da7 )
by Stefano
03:12
created

Events::triggerOnce()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 4
c 0
b 0
f 0
nc 1
nop 1
dl 0
loc 5
rs 9.4285
1
<?php
2
3
/**
4
 * Events trait
5
 *
6
 * Add to a class 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 {
0 ignored issues
show
Coding Style Compatibility introduced by
Each trait must be in a namespace of at least one level (a top-level vendor name)

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
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