|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace kalanis\kw_forms\Cache; |
|
4
|
|
|
|
|
5
|
|
|
|
|
6
|
|
|
use kalanis\kw_forms\Cache\Formats\Serialize; |
|
7
|
|
|
use kalanis\kw_forms\Interfaces\ICachedFormat; |
|
8
|
|
|
use kalanis\kw_storage\Interfaces\ITarget; |
|
9
|
|
|
use kalanis\kw_storage\StorageException; |
|
10
|
|
|
|
|
11
|
|
|
|
|
12
|
|
|
class Storage |
|
13
|
|
|
{ |
|
14
|
|
|
protected ?ITarget $target = null; |
|
15
|
|
|
protected Key $key; |
|
16
|
|
|
protected ICachedFormat $format; |
|
17
|
|
|
|
|
18
|
5 |
|
public function __construct(?ITarget $target = null, ?ICachedFormat $format = null) |
|
19
|
|
|
{ |
|
20
|
5 |
|
$this->target = $target; |
|
21
|
5 |
|
$this->key = new Key(); |
|
22
|
5 |
|
$this->format = $format ?: new Serialize(); |
|
23
|
5 |
|
} |
|
24
|
|
|
|
|
25
|
5 |
|
public function setAlias(string $alias = ''): void |
|
26
|
|
|
{ |
|
27
|
5 |
|
$this->key->setAlias($alias); |
|
28
|
5 |
|
} |
|
29
|
|
|
|
|
30
|
|
|
/** |
|
31
|
|
|
* Check if data are stored |
|
32
|
|
|
* @throws StorageException |
|
33
|
|
|
* @return bool |
|
34
|
|
|
*/ |
|
35
|
4 |
|
public function isStored(): bool |
|
36
|
|
|
{ |
|
37
|
4 |
|
if (!$this->target) { |
|
38
|
1 |
|
return false; |
|
39
|
|
|
} |
|
40
|
3 |
|
return $this->target->exists($this->key->fromSharedKey('')); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* Save form data into storage |
|
45
|
|
|
* @param array<string, string|int|float|bool|null> $values |
|
46
|
|
|
* @param int|null $timeout |
|
47
|
|
|
* @throws StorageException |
|
48
|
|
|
* @return bool |
|
49
|
|
|
*/ |
|
50
|
4 |
|
public function store(array $values, ?int $timeout = null): bool |
|
51
|
|
|
{ |
|
52
|
4 |
|
if (!$this->target) { |
|
53
|
1 |
|
return false; |
|
54
|
|
|
} |
|
55
|
3 |
|
return $this->target->save($this->key->fromSharedKey(''), $this->format->pack($values), $timeout); |
|
56
|
|
|
} |
|
57
|
|
|
|
|
58
|
|
|
/** |
|
59
|
|
|
* Read data from storage |
|
60
|
|
|
* @throws StorageException |
|
61
|
|
|
* @return array<string, string|int|float|bool|null> |
|
62
|
|
|
*/ |
|
63
|
4 |
|
public function load(): array |
|
64
|
|
|
{ |
|
65
|
4 |
|
if (!$this->target) { |
|
66
|
1 |
|
return []; |
|
67
|
|
|
} |
|
68
|
3 |
|
return $this->format->unpack($this->target->load($this->key->fromSharedKey(''))); |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
/** |
|
72
|
|
|
* Remove data from storage |
|
73
|
|
|
* @throws StorageException |
|
74
|
|
|
* @return bool |
|
75
|
|
|
*/ |
|
76
|
4 |
|
public function delete(): bool |
|
77
|
|
|
{ |
|
78
|
4 |
|
if (!$this->target) { |
|
79
|
1 |
|
return false; |
|
80
|
|
|
} |
|
81
|
3 |
|
return $this->target->remove($this->key->fromSharedKey('')); |
|
82
|
|
|
} |
|
83
|
|
|
} |
|
84
|
|
|
|