Completed
Push — master ( a1c249...c4799c )
by Taosikai
29:01 queued 16:32
created

CallableListener   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 80
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 0

Importance

Changes 0
Metric Value
wmc 8
lcom 2
cbo 0
dl 0
loc 80
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getCallable() 0 4 1
A handle() 0 4 1
A createFromCallable() 0 6 1
A findByCallable() 0 10 3
A clearListeners() 0 4 1
1
<?php
2
3
/*
4
 * This file is part of the slince/event-dispatcher package.
5
 *
6
 * (c) Slince <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Slince\EventDispatcher;
13
14
class CallableListener implements ListenerInterface
15
{
16
    /**
17
     * The callable callback.
18
     *
19
     * @var callable
20
     */
21
    protected $callable;
22
23
    /**
24
     * Array of callable-listeners.
25
     *
26
     * @var array
27
     */
28
    protected static $listeners = [];
29
30
    public function __construct($callable)
31
    {
32
        $this->callable = $callable;
33
        static::$listeners[] = $this;
34
    }
35
36
    /**
37
     * Gets callback.
38
     *
39
     * @return callable
40
     */
41
    public function getCallable()
42
    {
43
        return $this->callable;
44
    }
45
46
    /**
47
     * {@inheritdoc}
48
     */
49
    public function handle(Event $event)
50
    {
51
        call_user_func($this->callable, $event);
52
    }
53
54
    /**
55
     * Creates a callable-listener.
56
     *
57
     * @param callable $callable
58
     *
59
     * @return CallableListener
60
     */
61
    public static function createFromCallable($callable)
62
    {
63
        $listener = new static($callable);
64
65
        return $listener;
66
    }
67
68
    /**
69
     * Finds the listener from the collection by its callable.
70
     *
71
     * @param callable $callable
72
     *
73
     * @return CallableListener|false
74
     */
75
    public static function findByCallable($callable)
76
    {
77
        foreach (static::$listeners as $listener) {
78
            if ($listener->getCallable() == $callable) {
79
                return $listener;
80
            }
81
        }
82
83
        return false;
84
    }
85
86
    /**
87
     * Removes all registered callable-listeners.
88
     */
89
    public static function clearListeners()
90
    {
91
        static::$listeners = [];
92
    }
93
}
94