1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Mutex; |
6
|
|
|
|
7
|
|
|
use ErrorException; |
8
|
|
|
use Throwable; |
9
|
|
|
use Yiisoft\Mutex\Exception\MutexLockedException; |
10
|
|
|
|
11
|
|
|
use function error_reporting; |
12
|
|
|
use function restore_error_handler; |
13
|
|
|
use function set_error_handler; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Executes a callback in synchronized mode, i.e. only a single instance of the callback is executed at the same time: |
17
|
|
|
* |
18
|
|
|
* ```php |
19
|
|
|
* $synchronizer = new \Yiisoft\Mutex\Synchronizer(new MyMutexFactory()); |
20
|
|
|
* |
21
|
|
|
* $newCount = $synchronizer->execute('critical_logic', function () { |
22
|
|
|
* return $counter->increase(); |
23
|
|
|
* }, 10); |
24
|
|
|
* ``` |
25
|
|
|
*/ |
26
|
|
|
final class Synchronizer |
27
|
|
|
{ |
28
|
3 |
|
public function __construct(private MutexFactoryInterface $mutexFactory) |
29
|
|
|
{ |
30
|
3 |
|
} |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* Executes a PHP callable with a lock and returns the result. |
34
|
|
|
* |
35
|
|
|
* @param string $name Name of the mutex to acquire. |
36
|
|
|
* @param callable $callback PHP callable to execution. |
37
|
|
|
* @param int $timeout Time (in seconds) to wait for lock to be released. Defaults to zero meaning that |
38
|
|
|
* method {@see MutexInterface::acquire()} will return false immediately in case lock was already acquired. |
39
|
|
|
* |
40
|
|
|
* @throws MutexLockedException If unable to acquire lock. |
41
|
|
|
* @throws Throwable If an error occurred during the execution of the PHP callable. |
42
|
|
|
* |
43
|
|
|
* @return mixed The result of the PHP callable execution. |
44
|
|
|
*/ |
45
|
3 |
|
public function execute(string $name, callable $callback, int $timeout = 0) |
46
|
|
|
{ |
47
|
3 |
|
$mutex = $this->mutexFactory->createAndAcquire($name, $timeout); |
48
|
|
|
|
49
|
3 |
|
set_error_handler(static function (int $severity, string $message, string $file, int $line): bool { |
50
|
|
|
if (!(error_reporting() & $severity)) { |
51
|
|
|
// This error code is not included in error_reporting. |
52
|
|
|
return true; |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
throw new ErrorException($message, $severity, $severity, $file, $line); |
56
|
3 |
|
}); |
57
|
|
|
|
58
|
|
|
try { |
59
|
|
|
/** @var mixed $result */ |
60
|
3 |
|
return $callback(); |
61
|
|
|
} finally { |
62
|
3 |
|
restore_error_handler(); |
63
|
3 |
|
$mutex->release(); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|