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

SimpleMutex::acquire()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 8
ccs 0
cts 6
cp 0
crap 6
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Mutex;
6
7
/**
8
 * Simplest way to use mutex:
9
 *
10
 * ```
11
 * $mutex = $simpleMutex->acquire('critical_logic');
12
 * if (!$mutex->acquire(1000)) {
13
 *     throw new \RuntimeException('Unable to acquire "critical_logic" mutex.');
14
 * }
15
 *
16
 * // ...
17
 * // business logic execution
18
 * // ...
19
 *
20
 * $mutex->release();
21
 * ```
22
 */
23
final class SimpleMutex
24
{
25
    private MutexFactoryInterface $mutexFactory;
26
27
    /**
28
     * @var MutexInterface[]
29
     */
30
    private array $acquired = [];
31
32
    public function __construct(MutexFactoryInterface $mutexFactory)
33
    {
34
        $this->mutexFactory = $mutexFactory;
35
    }
36
37
    /**
38
     * Acquires a lock with a given name.
39
     *
40
     * @param string $name Name of the mutex to acquire.
41
     * @param int $timeout Time (in seconds) to wait for lock to be released. Defaults to zero meaning that method
42
     * will return false immediately in case lock was already acquired.
43
     */
44
    public function acquire(string $name, int $timeout = 0): bool
45
    {
46
        $mutex = $this->mutexFactory->create($name);
47
        if ($mutex->acquire($timeout)) {
48
            $this->acquired[$name] = $mutex;
49
            return true;
50
        }
51
        return false;
52
    }
53
54
    /**
55
     * Releases a lock with a given name.
56
     */
57
    public function release(string $name): void
58
    {
59
        if (!isset($this->acquired[$name])) {
60
            return;
61
        }
62
        $this->acquired[$name]->release();
63
    }
64
}
65