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

RedisTrait::unlock()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 2
dl 0
loc 3
ccs 2
cts 2
cp 1
crap 1
rs 10
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