1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace kalanis\kw_cache\Cache; |
4
|
|
|
|
5
|
|
|
|
6
|
|
|
use kalanis\kw_cache\CacheException; |
7
|
|
|
use kalanis\kw_cache\Interfaces\ICache; |
8
|
|
|
use kalanis\kw_semaphore\Interfaces\ISemaphore; |
9
|
|
|
use kalanis\kw_semaphore\SemaphoreException; |
10
|
|
|
|
11
|
|
|
|
12
|
|
|
/** |
13
|
|
|
* Class Semaphore |
14
|
|
|
* @package kalanis\kw_cache\Cache |
15
|
|
|
* Caching content in any cache - semaphore for detection |
16
|
|
|
*/ |
17
|
|
|
class Semaphore implements ICache |
18
|
|
|
{ |
19
|
|
|
protected ICache $cache; |
20
|
|
|
protected ISemaphore $reloadSemaphore; |
21
|
|
|
|
22
|
4 |
|
public function __construct(ICache $cache, ISemaphore $reloadSemaphore) |
23
|
|
|
{ |
24
|
4 |
|
$this->cache = $cache; |
25
|
4 |
|
$this->reloadSemaphore = $reloadSemaphore; |
26
|
4 |
|
} |
27
|
|
|
|
28
|
2 |
|
public function init(array $what): void |
29
|
|
|
{ |
30
|
2 |
|
$this->cache->init($what); |
31
|
2 |
|
} |
32
|
|
|
|
33
|
4 |
|
public function exists(): bool |
34
|
|
|
{ |
35
|
|
|
try { |
36
|
4 |
|
return $this->cache->exists() && !$this->reloadSemaphore->has(); |
37
|
1 |
|
} catch (SemaphoreException $ex) { |
38
|
1 |
|
throw new CacheException($ex->getMessage(), $ex->getCode(), $ex); |
39
|
|
|
} |
40
|
|
|
} |
41
|
|
|
|
42
|
3 |
|
public function set(string $content): bool |
43
|
|
|
{ |
44
|
3 |
|
$result = $this->cache->set($content); |
45
|
3 |
|
if (false === $result) { |
46
|
1 |
|
return false; |
47
|
|
|
} |
48
|
|
|
// remove signal to save |
49
|
|
|
try { |
50
|
2 |
|
if ($this->reloadSemaphore->has()) { |
51
|
2 |
|
$this->reloadSemaphore->remove(); |
52
|
|
|
} |
53
|
1 |
|
} catch (SemaphoreException $ex) { |
54
|
1 |
|
throw new CacheException($ex->getMessage(), $ex->getCode(), $ex); |
55
|
|
|
} |
56
|
2 |
|
return true; |
57
|
|
|
} |
58
|
|
|
|
59
|
3 |
|
public function get(): string |
60
|
|
|
{ |
61
|
3 |
|
return $this->exists() ? $this->cache->get() : '' ; |
62
|
|
|
} |
63
|
|
|
|
64
|
1 |
|
public function clear(): void |
65
|
|
|
{ |
66
|
1 |
|
$this->cache->clear(); |
67
|
1 |
|
} |
68
|
|
|
} |
69
|
|
|
|