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
|
|
|
|
9
|
|
|
class RedisCounter implements Counter |
10
|
|
|
{ |
11
|
|
|
private $redis; |
12
|
|
|
|
13
|
8 |
|
public function __construct(Client $redis) { |
14
|
8 |
|
$this->redis = $redis; |
15
|
|
|
} |
16
|
|
|
|
17
|
2 |
View Code Duplication |
public function increment(string $key): Promise { |
|
|
|
|
18
|
|
|
return \Amp\resolve(function() use ($key) { |
19
|
|
|
try { |
20
|
2 |
|
return yield $this->redis->incr($key); |
21
|
1 |
|
} catch (RedisException $e) { |
22
|
1 |
|
throw new StorageFailedException('Failed to increment counter.', 0, $e); |
23
|
|
|
} |
24
|
2 |
|
}); |
25
|
|
|
} |
26
|
|
|
|
27
|
2 |
View Code Duplication |
public function decrement(string $key): Promise { |
|
|
|
|
28
|
|
|
return \Amp\resolve(function() use ($key) { |
29
|
|
|
try { |
30
|
2 |
|
return yield $this->redis->decr($key); |
31
|
1 |
|
} catch (RedisException $e) { |
32
|
1 |
|
throw new StorageFailedException('Failed to decrement counter.', 0, $e); |
33
|
|
|
} |
34
|
2 |
|
}); |
35
|
|
|
} |
36
|
|
|
|
37
|
2 |
|
public function get(string $key): Promise { |
38
|
|
|
return \Amp\resolve(function() use ($key) { |
39
|
|
|
try { |
40
|
2 |
|
$result = yield $this->redis->get($key); |
41
|
|
|
|
42
|
1 |
|
return empty($result) ? 0 : (int) $result; |
43
|
1 |
|
} catch (RedisException $e) { |
44
|
1 |
|
throw new StorageFailedException('Failed to get counter.', 0, $e); |
45
|
|
|
} |
46
|
2 |
|
}); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
View Code Duplication |
public function set(string $key, int $val): Promise { |
|
|
|
|
50
|
2 |
|
return \Amp\resolve(function() use ($key, $val) { |
51
|
|
|
try { |
52
|
2 |
|
return yield $this->redis->set($key, $val); |
53
|
1 |
|
} catch (RedisException $e) { |
54
|
1 |
|
throw new StorageFailedException('Failed to set counter value.', 0, $e); |
55
|
|
|
} |
56
|
2 |
|
}); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
|
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.