GracefulShutdown::signalReceived()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 0
dl 0
loc 3
rs 10
1
<?php declare(strict_types=1);
2
3
namespace LeoCarmo\GracefulShutdown;
4
5
/**
6
 * Class GracefulShutdown
7
 *
8
 * @requires https://www.php.net/manual/pt_BR/book.pcntl.php
9
 *
10
 * @package LeoCarmo\GracefulShutdown
11
 */
12
class GracefulShutdown
13
{
14
    /**
15
     * @var int|null
16
     */
17
    protected ?int $signal = null;
18
19
    /**
20
     * @var array
21
     */
22
    protected array $signals;
23
24
    /**
25
     * @var bool
26
     */
27
    protected bool $debug;
28
29
    /**
30
     * GracefulShutdown constructor
31
     *
32
     * @param array $signals
33
     * @param bool $debug
34
     */
35
    public function __construct(
36
        array $signals = [SIGTERM, SIGINT, SIGUSR1, SIGUSR2, SIGQUIT, SIGHUP],
37
        bool $debug = false
38
    ) {
39
        $this->signals = $signals;
40
        $this->debug = $debug;
41
        $this->registerSignals();
42
    }
43
44
    /**
45
     * @param int $signal
46
     */
47
    public function __invoke(int $signal)
48
    {
49
        $this->debug("##################### ---> Signal received: [{$signal}]");
50
        $this->signal = $signal;
51
    }
52
53
    /**
54
     * Check if a signal was sent
55
     *
56
     * @return bool
57
     */
58
    public function signalReceived(): bool
59
    {
60
        return is_int($this->signal);
61
    }
62
63
    /**
64
     * Enable async signals and register
65
     */
66
    protected function registerSignals(): void
67
    {
68
        pcntl_async_signals(true);
69
70
        foreach ($this->signals as $signal) {
71
            pcntl_signal($signal, $this);
72
        }
73
    }
74
75
    /**
76
     * @param string $string
77
     */
78
    protected function debug(string $string): void
79
    {
80
        if ($this->debug) {
81
            echo $string . PHP_EOL;
82
        }
83
    }
84
}
85