Passed
Push — main ( 223ead...e5cf91 )
by Mr.
47s queued 10s
created

RedisTrait::transaction()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2.2109

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 8
nc 2
nop 4
dl 0
loc 13
ccs 5
cts 8
cp 0.625
crap 2.2109
rs 10
c 1
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace LibraryCatalog\Service\Repository;
6
7
use Predis\Client;
8
9
trait RedisTrait
10
{
11
    /**
12
     * @param Client $predis
13
     * @param string $key
14
     * @param int $ttl
15
     */
16 7
    public function lock(Client $predis, string $key, int $ttl): void
17
    {
18 7
        while ($predis->get($key)) {
19
            usleep(50000);
20
        }
21 7
        $predis->setex($key, $ttl, true);
22 7
    }
23
24
    /**
25
     * @param Client $predis
26
     * @param string $key
27
     */
28 7
    public function unlock(Client $predis, string $key): void
29
    {
30 7
        $predis->del($key);
31 7
    }
32
33
    /**
34
     * @param Client $predis
35
     * @param string $key
36
     * @param int $ttl
37
     * @param \Closure $closure
38
     * @throws \Throwable
39
     * @return mixed
40
     */
41 7
    public function transaction(Client $predis, string $key, int $ttl, \Closure $closure)
42
    {
43 7
        $this->lock($predis, $key, $ttl);
44
        try {
45 7
            $res = $closure();
46
        } catch (\Exception | \Throwable $e) {
47
            $this->unlock($predis, $key);
48
            throw $e;
49
        }
50
        // Unlock in correct flow.
51 7
        $this->unlock($predis, $key);
52
53 7
        return $res;
54
    }
55
}
56