RedisLocator::initMasterDiscovery()   A
last analyzed

Complexity

Conditions 4
Paths 4

Size

Total Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 18
CRAP Score 4

Importance

Changes 0
Metric Value
dl 0
loc 25
ccs 18
cts 18
cp 1
rs 9.52
c 0
b 0
f 0
cc 4
nc 4
nop 0
crap 4
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Lamoda\RedisSentinel;
6
7
use PSRedis\Client;
8
use PSRedis\MasterDiscovery;
9
10
class RedisLocator
11
{
12
    /** @var array */
13
    private $redisConfig;
14
15
    /** @var array */
16
    private $redisSentinelConfig;
17
18
    /** @var MasterDiscovery */
19
    private $masterDiscovery;
20
21 7
    public function __construct(array $redisConfig, array $redisSentinelConfig)
22
    {
23 7
        $this->redisConfig = $redisConfig;
24 7
        $this->redisSentinelConfig = $redisSentinelConfig;
25
26 7
        $this->masterDiscovery = $this->initMasterDiscovery();
27 6
    }
28
29 6
    public function getRedisConfig(): RedisConfig
30
    {
31 6
        $redisConfig = $this->redisConfig;
32
33 6
        if ($this->masterDiscovery) {
34
            /** @var Client $master */
35 3
            $master = $this->masterDiscovery->getMaster();
36 2
            $redisConfig['host'] = $master->getIpAddress();
37 2
            $redisConfig['port'] = (int) $master->getPort();
38
        }
39
40 5
        return new RedisConfig($redisConfig);
41
    }
42
43 7
    private function initMasterDiscovery(): ?MasterDiscovery
44
    {
45 7
        $urls = trim((string) ($this->redisSentinelConfig['url'] ?? ''));
46 7
        if (empty($urls)) {
47 3
            return null;
48
        }
49
50 4
        $urls = preg_split('/[\s,;]+/', $urls);
51 4
        $masterDiscovery = new MasterDiscovery($this->redisSentinelConfig['redisName']);
52 4
        $backoffStrategy = new MasterDiscovery\BackoffStrategy\Incremental(100, 1.5);
53 4
        $backoffStrategy->setMaxAttempts(10);
54 4
        $masterDiscovery->setBackoffStrategy($backoffStrategy);
55 4
        foreach ($urls as $singleSentinelUrl) {
56 4
            $url = parse_url($singleSentinelUrl);
57 4
            if (false === $url) {
58 1
                throw new \InvalidArgumentException("Invalid Sentinel URL: $singleSentinelUrl");
59
            }
60 3
            $host = $url['host'] ?? $url['path'];
61 3
            $port = $url['port'] ?? 26379;
62 3
            $sentinel = new Client($host, $port);
63 3
            $masterDiscovery->addSentinel($sentinel);
64
        }
65
66 3
        return $masterDiscovery;
67
    }
68
}
69