Lines 76.92% 10 / 13
Functions and Methods 75.00% 3 / 4
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
SignalHandlers 76.92% 10 / 13 75.00% 3 / 4 8.79 0.00% 0 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 install 40.00% 2 / 5 0.00% 0 / 1 4.94
 removeAll 100.00% 3 / 3 100.00% 1 / 1 2
 handleStopSignal 100.00% 4 / 4 100.00% 1 / 1 2
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Broker;
6
7use Psr\Log\LoggerInterface;
8use Revolt\EventLoop;
9
10final class SignalHandlers
11{
12    /** @var list<string> */
13    private array $watchers = [];
14
15    public function __construct(
16        private readonly BrokerRun $run,
17        private readonly LoggerInterface $logger,
18    ) {}
19
20    public function install(): void
21    {
22        foreach ([\SIGTERM, \SIGINT] as $signal) {
23            try {
24                $this->watchers[] = EventLoop::unreference(EventLoop::onSignal($signal, $this->handleStopSignal(...)));
25            } catch (EventLoop\UnsupportedFeatureException) {
26                $this->logger->warning('Signal handling unavailable; shutdown will not be graceful.');
27
28                return;
29            }
30        }
31    }
32
33    public function removeAll(): void
34    {
35        foreach ($this->watchers as $watcher) {
36            EventLoop::cancel($watcher);
37        }
38
39        $this->watchers = [];
40    }
41
42    private function handleStopSignal(): void
43    {
44        if ($this->run->isStopping()) {
45            $this->run->killWorkersNow();
46
47            return;
48        }
49
50        $this->run->stop('signal');
51    }
52}