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

RetryAcquireTrait::retryAcquire()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

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