SimpleMutex::release()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 2

Importance

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