Lines 72.72% 8 / 11
Functions and Methods 33.33% 1 / 3
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
RedisStoreBackendFactory 72.72% 8 / 11 33.33% 1 / 3 7.99 0.00% 0 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 listSchemes 0.00% 0 / 1 0.00% 0 / 1 2
 createBackend 77.77% 7 / 9 0.00% 0 / 1 5.27
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Store\Redis;
6
7use Amp\Redis\Connection\SocketRedisConnector;
8use Amp\Redis\RedisConfig;
9use Amp\Redis\RedisException;
10use Amp\Socket\ConnectContext;
11use Stewart\Store\Exception\StoreSetupException;
12use Stewart\Store\StoreBackend;
13use Stewart\Store\StoreBackendFactory;
14use Stewart\Store\StoreDsn;
15use Stewart\Store\StoreTiming;
16use Stewart\Support\Time\Deadlines;
17
18use function Amp\Redis\createRedisClient;
19
20final readonly class RedisStoreBackendFactory implements StoreBackendFactory
21{
22    private const string TCP_SCHEME = 'redis';
23
24    private const string SOCKET_SCHEME = 'unix';
25
26    public function __construct(private Deadlines $deadlines) {}
27
28    public function listSchemes(): array
29    {
30        return [self::TCP_SCHEME, self::SOCKET_SCHEME];
31    }
32
33    public function createBackend(StoreDsn $dsn, StoreTiming $timing): StoreBackend
34    {
35        if (!\in_array($dsn->scheme, $this->listSchemes(), true)) {
36            throw StoreSetupException::schemeUnsupported($dsn->scheme, $this->listSchemes());
37        }
38
39        if ($dsn->scheme === self::TCP_SCHEME && !\is_string(parse_url($dsn->reveal(), \PHP_URL_HOST))) {
40            throw StoreSetupException::dsnInvalid($dsn->reveal());
41        }
42
43        try {
44            $config = RedisConfig::fromUri($dsn->reveal(), $timing->timeout->toSeconds());
45        } catch (RedisException) {
46            // Not chained: amphp's message contains the URI and its password.
47            throw StoreSetupException::dsnInvalid($dsn->reveal());
48        }
49
50        $connector = new SocketRedisConnector($config->getConnectUri(), new ConnectContext()->withConnectTimeout($config->getTimeout())->withTcpNoDelay());
51
52        return new RedisStoreBackend(createRedisClient($config, $connector), $dsn, $timing, $this->deadlines);
53    }
54}