Passed
Pull Request — master (#30)
by Sergei
04:38 queued 02:31
created

Mutex::acquire()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3

Importance

Changes 0
Metric Value
eloc 4
dl 0
loc 9
ccs 5
cts 5
cp 1
rs 10
c 0
b 0
f 0
cc 3
nc 2
nop 2
crap 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Mutex;
6
7
use RuntimeException;
8
9
use function in_array;
10
11
/**
12
 * The Mutex component allows mutual execution of concurrent processes in order to prevent "race conditions".
13
 *
14
 * This is achieved by using a "lock" mechanism. Each possibly concurrent thread cooperates by acquiring
15
 * a lock before accessing the corresponding data.
16
 *
17
 * Usage example:
18
 *
19
 * ```
20
 * $lock = $mutex->acquire($mutexName);
21
 * // ...
22
 * // business logic execution
23
 * // ...
24
 * $lock->release();
25
 * ```
26
 *
27
 * This is a base class, which should be extended in order to implement the actual lock mechanism.
28
 */
29
abstract class Mutex implements MutexInterface
30
{
31
    /**
32
     * @var string[] Names of the locks acquired by the current PHP process.
33
     */
34
    private array $locks = [];
35
36
    /**
37
     * Mutex constructor.
38
     *
39
     * @param bool $autoRelease Whether all locks acquired in this process (i.e. local locks) must be released
40
     * automatically before finishing script execution. Defaults to true. Setting this property
41
     * to true means that all locks acquired in this process must be released (regardless of
42
     * errors or exceptions).
43
     */
44 10
    public function __construct(bool $autoRelease = true)
45
    {
46 10
        if ($autoRelease) {
47
            $locks = &$this->locks;
48
            register_shutdown_function(function () use (&$locks) {
49
                /** @var string $lock */
50
                foreach ($locks as $lock) {
51
                    $this->release($lock);
52
                }
53
            });
54
        }
55 10
    }
56
57
    /**
58
     * Acquires a lock by name.
59
     *
60
     * @param string $name Name of the lock to be acquired. Must be unique.
61
     * @param int $timeout Time (in seconds) to wait for lock to be released. Defaults to zero meaning that method
62
     * will return false immediately in case lock was already acquired.
63
     *
64
     * @return MutexLockInterface
65
     */
66 7
    public function acquire(string $name, int $timeout = 0): MutexLockInterface
67
    {
68 7
        if (!in_array($name, $this->locks, true) && $this->acquireLock($name, $timeout)) {
69 7
            $this->locks[] = $name;
70
71 7
            return new MutexLock($this, $name);
72
        }
73
74 3
        throw new MutexLockedException();
75
    }
76
77
    /**
78
     * Releases acquired lock. This method will return false in case the lock was not found.
79
     *
80
     * @param string $name Name of the lock to be released. This lock must already exist.
81
     */
82 6
    public function release(string $name): void
83
    {
84 6
        if ($this->releaseLock($name)) {
85 3
            $index = array_search($name, $this->locks, true);
86 3
            if ($index !== false) {
87 3
                unset($this->locks[$index]);
88
            }
89
90 3
            return;
91
        }
92
93 3
        throw new RuntimeException();
94
    }
95
96
    /**
97
     * This method should be extended by a concrete Mutex implementations. Acquires lock by name.
98
     *
99
     * @param string $name Name of the lock to be acquired.
100
     * @param int $timeout Time (in seconds) to wait for the lock to be released.
101
     *
102
     * @return bool Acquiring result.
103
     */
104
    abstract protected function acquireLock(string $name, int $timeout = 0): bool;
105
106
    /**
107
     * This method should be extended by a concrete Mutex implementations. Releases lock by given name.
108
     *
109
     * @param string $name Name of the lock to be released.
110
     *
111
     * @return bool Release result.
112
     */
113
    abstract protected function releaseLock(string $name): bool;
114
}
115