RedisSequenceResolver::setCachePrefix()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 6
ccs 0
cts 5
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 2
1
<?php
2
3
/*
4
 * This file is part of the godruoyi/php-snowflake.
5
 *
6
 * (c) Godruoyi <[email protected]>
7
 *
8
 * This source file is subject to the MIT license that is bundled.
9
 */
10
11
namespace Godruoyi\Snowflake;
12
13
use Redis;
14
use RedisException;
15
16
class RedisSequenceResolver implements SequenceResolver
17
{
18
    /**
19
     * The redis client instance.
20
     *
21
     * @var \Redis
22
     */
23
    protected $redis;
24
25
    /**
26
     * The cache prefix.
27
     *
28
     * @var string
29
     */
30
    protected $prefix;
31
32
    /**
33
     * Init resolve instance, must connectioned.
34
     */
35
    public function __construct(Redis $redis)
36
    {
37
        if ($redis->ping()) {
38
            $this->redis = $redis;
39
40
            return;
41
        }
42
43
        throw new RedisException('Redis server went away');
44
    }
45
46
    /**
47
     *  {@inheritdoc}
48
     */
49
    public function sequence(int $currentTime)
50
    {
51
        $lua = "return redis.call('exists',KEYS[1])<1 and redis.call('psetex',KEYS[1],ARGV[2],ARGV[1])";
52
53
        if ($this->redis->eval($lua, [($key = $this->prefix.$currentTime), 1, 1000], 1)) {
54
            return 0;
55
        }
56
57
        return $this->redis->incrby($key, 1);
58
    }
59
60
    /**
61
     * Set cacge prefix.
62
     */
63
    public function setCachePrefix(string $prefix)
64
    {
65
        $this->prefix = $prefix;
66
67
        return $this;
68
    }
69
}
70