-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathSignalSocketHelper.php
80 lines (60 loc) · 1.92 KB
/
SignalSocketHelper.php
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
<?php
declare(strict_types=1);
namespace Enqueue\AmqpTools;
class SignalSocketHelper
{
/**
* @var callable[]
*/
private $handlers;
/**
* @var bool
*/
private $wasThereSignal;
public function __construct()
{
$this->handlers = [];
}
public function beforeSocket(): void
{
// PHP 7.1 and pcntl ext installed higher
if (false == function_exists('pcntl_signal_get_handler')) {
return;
}
$signals = [\SIGTERM, \SIGQUIT, \SIGINT];
if ($this->handlers) {
throw new \LogicException('The handlers property should be empty but it is not. The afterSocket method might not have been called.');
}
if (null !== $this->wasThereSignal) {
throw new \LogicException('The wasThereSignal property should be null but it is not. The afterSocket method might not have been called.');
}
$this->wasThereSignal = false;
foreach ($signals as $signal) {
/** @var callable $handler */
$handler = pcntl_signal_get_handler($signal);
pcntl_signal($signal, function ($signal) use ($handler) {
$this->wasThereSignal = true;
$handler && $handler($signal);
});
$handler && $this->handlers[$signal] = $handler;
}
}
public function afterSocket(): void
{
// PHP 7.1 and higher
if (false == function_exists('pcntl_signal_get_handler')) {
return;
}
$signals = [\SIGTERM, \SIGQUIT, \SIGINT];
$this->wasThereSignal = null;
foreach ($signals as $signal) {
$handler = isset($this->handlers[$signal]) ? $this->handlers[$signal] : \SIG_DFL;
pcntl_signal($signal, $handler);
}
$this->handlers = [];
}
public function wasThereSignal(): bool
{
return (bool) $this->wasThereSignal;
}
}