Lines 100.00% 9 / 9
Functions and Methods 100.00% 3 / 3
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
ShutdownTrait 100.00% 9 / 9 100.00% 3 / 3 7 100.00% 1 / 1
 setShutdown 100.00% 2 / 2 100.00% 1 / 1 1
 shouldShutdown 100.00% 5 / 5 100.00% 1 / 1 4
 checkShutdown 100.00% 2 / 2 100.00% 1 / 1 2
1<?php
2
3declare(strict_types=1);
4
5namespace Tomaj\Hermes\Driver;
6
7use DateTimeImmutable;
8use Tomaj\Hermes\Shutdown\ShutdownException;
9use Tomaj\Hermes\Shutdown\ShutdownInterface;
10use Tomaj\Hermes\Shutdown\SignalStop;
11
12trait ShutdownTrait
13{
14    private ?ShutdownInterface $shutdown = null;
15
16    private ?DateTimeImmutable $startTime = null;
17
18    public function setShutdown(ShutdownInterface $shutdown): void
19    {
20        $this->shutdown = $shutdown;
21        $this->startTime = new DateTimeImmutable();
22    }
23
24    private function shouldShutdown(): bool
25    {
26        if (SignalStop::received() !== null) {
27            return true;
28        }
29        if ($this->shutdown === null || $this->startTime === null) {
30            return false;
31        }
32        return $this->shutdown->shouldShutdown($this->startTime);
33    }
34
35    /**
36     * @throws ShutdownException
37     */
38    private function checkShutdown(): void
39    {
40        if ($this->shouldShutdown()) {
41            throw new ShutdownException();
42        }
43    }
44}