Completed
Branch master (c4b56e)
by Andrey
03:02 queued 01:04
created

ListenerQueue::eject()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 16
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 9
nc 3
nop 1
1
<?php
2
3
namespace Event;
4
5
class ListenerQueue
6
{
7
    private $listeners = [];
8
9
    /**
10
     * Add listener to queue with priority
11
     * 
12
     * @param callable $callback
13
     * @param int $priority
14
     * @return void
15
     */
16
    public function add(callable $callback, $priority)
17
    {
18
        $this->eject($callback);
19
20
        $this->listeners[] = [
21
            'callback' => $callback,
22
            'priority' => $priority
23
        ];
24
25
        $this->lsort();
26
    }
27
28
    /**
29
     * Get listeners array
30
     * 
31
     * @return array
32
     */
33
    public function get()
34
    {
35
        return $this->listeners;
36
    }
37
38
    /**
39
     * Remove listener from listeners
40
     * 
41
     * @param callable $callback
42
     * @return bool true on success false on failure
43
     */
44
    public function eject(callable $callback)
45
    {
46
        $flag = false;
47
        foreach ($this->listeners as $key => $value)
48
        {
49
            $finded = in_array($callback, $value, true);
50
            if ($finded)
51
            {
52
                unset($this->listeners[$key]);
53
                $flag = true;
54
            }
55
        }
56
57
        $this->lsort();
58
        return $flag;
59
    }
60
61
    /**
62
     * Validate listeners queue (is exist)
63
     * 
64
     * @return bool true on success false on failure
65
     */
66
    public function valid()
67
    {
68
        if (sizeof($this->listeners) == 0) {
69
            return false;
70
        }
71
72
        return true;
73
    }
74
75
    /**
76
     * Clear listener queue
77
     * 
78
     * @return void
79
     */
80
    public function clear()
81
    {
82
        $this->listeners = [];
83
    }
84
85
    /**
86
     * Sorting listeners in priority
87
     * 
88
     * @return void
89
     */
90
    private function lsort()
91
    {
92
        uasort($this->listeners, function($a, $b) {
93
            if ($a['priority'] == $b['priority']) {
94
                return 0;
95
            }
96
            return ($a['priority'] > $b['priority']) ? -1 : 1;
97
        });
98
    }
99
}