1
|
|
|
<?php declare(strict_types=1); |
2
|
|
|
|
3
|
|
|
namespace ekinhbayar\GitAmp\Storage; |
4
|
|
|
|
5
|
|
|
use Amp\Promise; |
6
|
|
|
use Amp\Redis\Client; |
7
|
|
|
use Amp\Redis\RedisException; |
8
|
|
|
use function Amp\resolve; |
9
|
|
|
|
10
|
|
|
class RedisCounter implements Counter { |
11
|
|
|
const SCRIPT_DECREMENT = <<<SCRIPT |
12
|
|
|
local count = redis.call('decr', KEYS[1]) |
13
|
|
|
|
14
|
|
|
if count == 0 then |
15
|
|
|
redis.call('del', KEYS[1]) |
16
|
|
|
return 0 |
17
|
|
|
else |
18
|
|
|
return count |
19
|
|
|
end |
20
|
|
|
SCRIPT; |
21
|
|
|
|
22
|
|
|
private $redis; |
23
|
|
|
|
24
|
|
|
public function __construct(Client $redis) { |
25
|
|
|
$this->redis = $redis; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
View Code Duplication |
public function increment(string $key): Promise { |
|
|
|
|
29
|
|
|
return resolve(function () use ($key) { |
30
|
|
|
try { |
31
|
|
|
return yield $this->redis->incr($key); |
32
|
|
|
} catch (RedisException $e) { |
33
|
|
|
throw new StorageFailedException("Failed to increment counter.", 0, $e); |
|
|
|
|
34
|
|
|
} |
35
|
|
|
}); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
View Code Duplication |
public function decrement(string $key): Promise { |
|
|
|
|
39
|
|
|
return resolve(function () use ($key) { |
40
|
|
|
try { |
41
|
|
|
return yield $this->redis->eval(self::SCRIPT_DECREMENT, [$key], []); |
42
|
|
|
} catch (RedisException $e) { |
43
|
|
|
throw new StorageFailedException("Failed to decrement counter.", 0, $e); |
|
|
|
|
44
|
|
|
} |
45
|
|
|
}); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
public function get(string $key): Promise { |
49
|
|
|
return resolve(function () use ($key) { |
50
|
|
|
try { |
51
|
|
|
$result = yield $this->redis->get($key); |
52
|
|
|
|
53
|
|
|
return empty($result) ? 0 : (int) $result; |
54
|
|
|
} catch (RedisException $e) { |
55
|
|
|
throw new StorageFailedException("Failed to get counter.", 0, $e); |
|
|
|
|
56
|
|
|
} |
57
|
|
|
}); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
View Code Duplication |
public function set(string $key, int $val): Promise { |
|
|
|
|
61
|
|
|
return resolve(function () use ($key, $val) { |
62
|
|
|
try { |
63
|
|
|
return yield $this->redis->set($key, $val); |
64
|
|
|
} catch (RedisException $e) { |
65
|
|
|
throw new StorageFailedException("Failed to set counter value.", 0, $e); |
|
|
|
|
66
|
|
|
} |
67
|
|
|
}); |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.