forked from reactphp/event-loop
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSignalsHandler.php
More file actions
97 lines (78 loc) · 2.23 KB
/
SignalsHandler.php
File metadata and controls
97 lines (78 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php
namespace React\EventLoop;
use React\EventLoop\TimerInterface;
/**
* @internal
*/
final class SignalsHandler
{
private $loop;
private $timer;
private $signals = [];
private $on;
private $off;
public function __construct(LoopInterface $loop, callable $on, callable $off)
{
$this->loop = $loop;
$this->on = $on;
$this->off = $off;
}
public function __destruct()
{
$off = $this->off;
foreach ($this->signals as $signal => $listeners) {
$off($signal);
}
}
public function add($signal, callable $listener)
{
if (count($this->signals) == 0 && $this->timer === null) {
/**
* Timer to keep the loop alive as long as there are any signal handlers registered
*/
$this->timer = $this->loop->addPeriodicTimer(300, function () {});
}
if (!isset($this->signals[$signal])) {
$this->signals[$signal] = [];
$on = $this->on;
$on($signal);
}
if (in_array($listener, $this->signals[$signal])) {
return;
}
$this->signals[$signal][] = $listener;
}
public function remove($signal, callable $listener)
{
if (!isset($this->signals[$signal])) {
return;
}
$index = \array_search($listener, $this->signals[$signal], true);
unset($this->signals[$signal][$index]);
if (isset($this->signals[$signal]) && \count($this->signals[$signal]) === 0) {
unset($this->signals[$signal]);
$off = $this->off;
$off($signal);
}
if (count($this->signals) == 0 && $this->timer instanceof TimerInterface) {
$this->loop->cancelTimer($this->timer);
$this->timer = null;
}
}
public function call($signal)
{
if (!isset($this->signals[$signal])) {
return;
}
foreach ($this->signals[$signal] as $listener) {
\call_user_func($listener, $signal);
}
}
public function count($signal)
{
if (!isset($this->signals[$signal])) {
return 0;
}
return \count($this->signals[$signal]);
}
}