-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWrappingCriticalSection.php
53 lines (45 loc) · 1.65 KB
/
WrappingCriticalSection.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php
declare(strict_types=1);
namespace PetrKnap\CriticalSection;
use Symfony\Component\Lock\LockInterface;
abstract class WrappingCriticalSection extends CriticalSection
{
protected function __construct(
private readonly CriticalSection|null $wrappedCriticalSection,
bool $isBlocking,
) {
parent::__construct($isBlocking);
}
public function __invoke(callable $criticalSection, mixed ...$args): mixed
{
return parent::__invoke(function (mixed ...$args) use ($criticalSection) {
if ($this->wrappedCriticalSection) {
return ($this->wrappedCriticalSection)(static fn () => $criticalSection(...$args));
}
return $criticalSection(...$args);
}, ...$args);
}
public function withLock(LockInterface $lock, bool|null $isBlocking = null): WrappingCriticalSection
{
return match ($isBlocking) {
null => new Symfony\Lock\CriticalSection($lock, $this->getWrappingReferenceOrNull()),
default => new Symfony\Lock\CriticalSection($lock, $this->getWrappingReferenceOrNull(), $isBlocking),
};
}
/**
* @param array<LockInterface> $locks
*/
public function withLocks(array $locks, bool|null $isBlocking = null): WrappingCriticalSection
{
$locks = array_reverse($locks); // reverse array to keep order of locks during wrapping
$instance = $this;
foreach ($locks as $lock) {
$instance = $instance->withLock($lock, $isBlocking);
}
return $instance;
}
protected function getWrappingReferenceOrNull(): CriticalSection|null
{
return $this;
}
}