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