@@ -24,8 +24,7 @@ class DoubleCheckedLocking
24
24
private $ check ;
25
25
26
26
/**
27
- * @param callable(): bool $check Callback that decides if the lock should be acquired and is rechecked
28
- * after a lock has been acquired
27
+ * @param callable(): bool $check Decides if a lock should be acquired and is rechecked after the lock has been acquired
29
28
*/
30
29
public function __construct (Mutex $ mutex , callable $ check )
31
30
{
@@ -34,31 +33,36 @@ public function __construct(Mutex $mutex, callable $check)
34
33
}
35
34
36
35
/**
37
- * Executes a block of code only after the check callback passes
38
- * before and after acquiring a lock.
36
+ * Execute a block of code only after the check callback passes before and after acquiring a lock.
39
37
*
40
- * @template T
38
+ * @template TSuccess
39
+ * @template TFail
41
40
*
42
- * @param callable(): T $code
41
+ * @param callable(): TSuccess $successFx
42
+ * @param callable(): TFail $failFx
43
43
*
44
- * @return T |false False if check did not pass
44
+ * @return TSuccess|TFail |false False if check did not pass
45
45
*
46
46
* @throws \Throwable
47
47
* @throws LockAcquireException
48
48
* @throws LockReleaseException
49
49
*/
50
- public function then (callable $ code )
50
+ public function then (callable $ successFx , callable $ failFx = null )
51
51
{
52
52
if (!($ this ->check )()) {
53
- return false ;
53
+ return $ failFx !== null
54
+ ? $ failFx ()
55
+ : false ;
54
56
}
55
57
56
- return $ this ->mutex ->synchronized (function () use ($ code ) {
58
+ return $ this ->mutex ->synchronized (function () use ($ successFx , $ failFx ) {
57
59
if (!($ this ->check )()) {
58
- return false ;
60
+ return $ failFx !== null
61
+ ? $ failFx ()
62
+ : false ;
59
63
}
60
64
61
- return $ code ();
65
+ return $ successFx ();
62
66
});
63
67
}
64
68
}
0 commit comments