Lines 100.00% 6 / 6
Functions and Methods 100.00% 3 / 3
Classes and Traits 100.00% 1 / 1
Name Lines Functions and Methods CRAP Classes and Traits
PredisShutdown 100.00% 6 / 6 100.00% 3 / 3 4 100.00% 1 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 shouldShutdown 100.00% 2 / 2 100.00% 1 / 1 2
 shutdown 100.00% 3 / 3 100.00% 1 / 1 1
1<?php
2
3declare(strict_types=1);
4
5namespace Tomaj\Hermes\Shutdown;
6
7use DateTimeImmutable;
8use DateTimeInterface;
9use Predis\Client;
10use Predis\Response\Status;
11
12/**
13 * Class PredisShutdown provides predis implementation of Tomaj\Hermes\Shutdown\ShutdownInterface
14 *
15 * Set the shutdown time (`"seconds.microseconds"`, a whole UNIX timestamp also works) to key `$key` (default `hermes_shutdown`) to shutdown Hermes worker.
16 */
17final readonly class PredisShutdown implements ShutdownInterface
18{
19    public function __construct(
20        private Client $redis,
21        private string $key = 'hermes_shutdown',
22    ) {}
23
24    /**
25     * Returns true when the stored shutdown time is not in the future
26     * and is later than the moment this worker started ($startTime).
27     */
28    #[\Override]
29    public function shouldShutdown(DateTimeInterface $startTime): bool
30    {
31        // a missing key reads as false (phpredis) or null (Predis), which parse() turns into null
32        $shutdownTime = ShutdownTime::parse($this->redis->get($this->key));
33
34        return $shutdownTime !== null && ShutdownTime::isRequested($shutdownTime, $startTime, microtime(true));
35    }
36
37    /**
38     * Sets to Redis value `$shutdownTime` (or the current time) to `$key` defined in constructor.
39     */
40    #[\Override]
41    public function shutdown(?DateTimeInterface $shutdownTime = null): bool
42    {
43        $shutdownTime ??= new DateTimeImmutable();
44
45        /** @var Status $response */
46        $response = $this->redis->set($this->key, ShutdownTime::format($shutdownTime));
47
48        return $response->getPayload() === 'OK';
49    }
50}