1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace kalanis\kw_locks\Methods; |
4
|
|
|
|
5
|
|
|
|
6
|
|
|
use kalanis\kw_locks\Interfaces\IKLTranslations; |
7
|
|
|
use kalanis\kw_locks\Interfaces\IPassedKey; |
8
|
|
|
use kalanis\kw_locks\LockException; |
9
|
|
|
use kalanis\kw_locks\Traits\TLang; |
10
|
|
|
use kalanis\kw_semaphore\Interfaces\ISemaphore; |
11
|
|
|
use kalanis\kw_semaphore\SemaphoreException; |
12
|
|
|
|
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Class SemaphoreLock |
16
|
|
|
* @package kalanis\kw_locks\Methods |
17
|
|
|
*/ |
18
|
|
|
class SemaphoreLock implements IPassedKey |
19
|
|
|
{ |
20
|
|
|
use TLang; |
21
|
|
|
|
22
|
|
|
protected ISemaphore $semaphore; |
23
|
|
|
/** @var string[] */ |
24
|
|
|
protected array $specialKey = []; |
25
|
|
|
protected string $checkContent = ''; |
26
|
|
|
|
27
|
4 |
|
public function __construct(ISemaphore $semaphore, ?IKLTranslations $lang = null) |
28
|
|
|
{ |
29
|
4 |
|
$this->semaphore = $semaphore; |
30
|
4 |
|
$this->setKlLang($lang); |
31
|
4 |
|
} |
32
|
|
|
|
33
|
4 |
|
public function __destruct() |
34
|
|
|
{ |
35
|
|
|
try { |
36
|
4 |
|
$this->delete(); |
37
|
3 |
|
} catch (LockException $ex) { |
38
|
|
|
// do nothing instead of |
39
|
|
|
// register_shutdown_function([$this, 'delete']); |
40
|
|
|
} |
41
|
4 |
|
} |
42
|
|
|
|
43
|
4 |
|
public function setKey(string $key, string $checkContent = ''): void |
44
|
|
|
{ |
45
|
4 |
|
} |
46
|
|
|
|
47
|
4 |
|
public function has(): bool |
48
|
|
|
{ |
49
|
|
|
try { |
50
|
4 |
|
return $this->semaphore->has(); |
51
|
3 |
|
} catch (SemaphoreException $ex) { |
52
|
3 |
|
throw new LockException($this->getKlLang()->iklProblemWithStorage(), $ex->getCode(), $ex); |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
56
|
2 |
|
public function create(bool $force = false): bool |
57
|
|
|
{ |
58
|
2 |
|
if (!$force && $this->has()) { |
59
|
1 |
|
return false; |
60
|
|
|
} |
61
|
|
|
try { |
62
|
2 |
|
return $this->semaphore->want(); |
63
|
1 |
|
} catch (SemaphoreException $ex) { |
64
|
1 |
|
throw new LockException($this->getKlLang()->iklProblemWithStorage(), $ex->getCode(), $ex); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|
68
|
4 |
|
public function delete(bool $force = false): bool |
69
|
|
|
{ |
70
|
4 |
|
if (!$force && !$this->has()) { |
71
|
1 |
|
return true; |
72
|
|
|
} |
73
|
|
|
try { |
74
|
2 |
|
return $this->semaphore->remove(); |
75
|
1 |
|
} catch (SemaphoreException $ex) { |
76
|
1 |
|
throw new LockException($this->getKlLang()->iklProblemWithStorage(), $ex->getCode(), $ex); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|