@@ -21,44 +21,53 @@ class DoubleCheckedLocking
2121 private Mutex $ mutex ;
2222
2323 /** @var callable(): bool */
24- private $ check ;
24+ private $ checkFx ;
2525
2626 /**
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 $checkFx Decides if a lock should be acquired and is rechecked after the lock has been acquired
2928 */
30- public function __construct (Mutex $ mutex , callable $ check )
29+ public function __construct (Mutex $ mutex , callable $ checkFx )
3130 {
3231 $ this ->mutex = $ mutex ;
33- $ this ->check = $ check ;
32+ $ this ->checkFx = $ checkFx ;
33+ }
34+
35+ private function invokeCheckFx (): bool
36+ {
37+ return ($ this ->checkFx )();
3438 }
3539
3640 /**
37- * Executes a block of code only after the check callback passes
38- * before and after acquiring a lock.
41+ * Execute a block of code only after the check callback passes before and after acquiring a lock.
3942 *
40- * @template T
43+ * @template TSuccess
44+ * @template TFail = never
4145 *
42- * @param callable(): T $code
46+ * @param callable(): TSuccess $successFx
47+ * @param callable(): TFail $failFx
4348 *
44- * @return T|false False if check did not pass
49+ * @return TSuccess|($failFx is null ? false : TFail)
4550 *
4651 * @throws \Throwable
4752 * @throws LockAcquireException
4853 * @throws LockReleaseException
4954 */
50- public function then (callable $ code )
55+ public function then (callable $ successFx , ? callable $ failFx = null )
5156 {
52- if (!($ this ->check )()) {
53- return false ;
57+ if (!$ this ->invokeCheckFx ()) {
58+ return $ failFx !== null
59+ ? $ failFx ()
60+ : false ;
5461 }
5562
56- return $ this ->mutex ->synchronized (function () use ($ code ) {
57- if (!($ this ->check )()) {
58- return false ;
63+ return $ this ->mutex ->synchronized (function () use ($ successFx , $ failFx ) {
64+ if (!$ this ->invokeCheckFx ()) {
65+ return $ failFx !== null
66+ ? $ failFx ()
67+ : false ;
5968 }
6069
61- return $ code ();
70+ return $ successFx ();
6271 });
6372 }
6473}
0 commit comments