Passed
Pull Request — master (#31)
by Evgeniy
02:29
created

RetryAcquireTrait   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 4
eloc 12
c 2
b 0
f 0
dl 0
loc 27
ccs 11
cts 11
cp 1
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A retryAcquire() 0 11 3
A withRetryDelay() 0 5 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Mutex;
6
7
use Closure;
8
9
/**
10
 * Allows retrying acquire with a certain timeout.
11
 */
12
trait RetryAcquireTrait
13
{
14
    /**
15
     * @var int Number of milliseconds between each try until specified timeout times out.
16
     * By default, it is 50 milliseconds - it means that we may try to acquire lock up to 20 times per
17
     * second.
18
     */
19
    private int $retryDelay = 50;
20
21 2
    public function withRetryDelay(int $retryDelay): self
22
    {
23 2
        $new = clone $this;
24 2
        $new->retryDelay = $retryDelay;
25 2
        return $new;
26
    }
27
28 2
    private function retryAcquire(int $timeout, Closure $callback): bool
29
    {
30 2
        $start = microtime(true);
31
        do {
32 2
            if ($callback()) {
33 1
                return true;
34
            }
35 2
            usleep($this->retryDelay * 1000);
36 2
        } while (microtime(true) - $start < $timeout);
37
38 1
        return false;
39
    }
40
}
41