1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace kalanis\kw_storage\Storage\Target; |
4
|
|
|
|
5
|
|
|
|
6
|
|
|
use kalanis\kw_storage\Interfaces\IStTranslations; |
7
|
|
|
use kalanis\kw_storage\Interfaces\Target\ITargetFlat; |
8
|
|
|
use kalanis\kw_storage\StorageException; |
9
|
|
|
use kalanis\kw_storage\Traits\TLang; |
10
|
|
|
use Traversable; |
11
|
|
|
|
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* Class Memory |
15
|
|
|
* @package kalanis\kw_storage\Storage\Target |
16
|
|
|
* Store content onto memory - TEMPORARY |
17
|
|
|
*/ |
18
|
|
|
class Memory implements ITargetFlat |
19
|
|
|
{ |
20
|
|
|
use TOperations; |
21
|
|
|
use TLang; |
22
|
|
|
|
23
|
|
|
/** @var array<string, string> */ |
24
|
|
|
protected array $data = []; |
25
|
|
|
|
26
|
19 |
|
public function __construct(?IStTranslations $lang = null) |
27
|
|
|
{ |
28
|
19 |
|
$this->setStLang($lang); |
29
|
|
|
} |
30
|
|
|
|
31
|
2 |
|
public function check(string $key): bool |
32
|
|
|
{ |
33
|
2 |
|
return true; |
34
|
|
|
} |
35
|
|
|
|
36
|
5 |
|
public function exists(string $key): bool |
37
|
|
|
{ |
38
|
5 |
|
return isset($this->data[$key]); |
39
|
|
|
} |
40
|
|
|
|
41
|
4 |
|
public function load(string $key): string |
42
|
|
|
{ |
43
|
4 |
|
if (!$this->exists($key)) { |
44
|
1 |
|
throw new StorageException($this->getStLang()->stCannotReadKey()); |
45
|
|
|
} |
46
|
3 |
|
return $this->data[$key]; |
47
|
|
|
} |
48
|
|
|
|
49
|
4 |
|
public function save(string $key, string $data, ?int $timeout = null): bool |
50
|
|
|
{ |
51
|
4 |
|
$this->data[$key] = $data; |
52
|
4 |
|
return true; |
53
|
|
|
} |
54
|
|
|
|
55
|
4 |
|
public function remove(string $key): bool |
56
|
|
|
{ |
57
|
4 |
|
if ($this->exists($key)) { |
58
|
4 |
|
unset($this->data[$key]); |
59
|
|
|
} |
60
|
4 |
|
return true; |
61
|
|
|
} |
62
|
|
|
|
63
|
1 |
|
public function lookup(string $path): Traversable |
64
|
|
|
{ |
65
|
1 |
|
$keyLen = mb_strlen($path); |
66
|
1 |
|
foreach ($this->data as $file => $entry) { |
67
|
1 |
|
if (boolval($keyLen) && (0 === mb_strpos($file, $path))) { |
68
|
1 |
|
yield mb_substr($file, $keyLen); |
69
|
1 |
|
} elseif (!boolval($keyLen)) { |
70
|
1 |
|
yield $file; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
75
|
2 |
|
public function increment(string $key, int $step = 1): bool |
76
|
|
|
{ |
77
|
2 |
|
if ($this->exists($key)) { |
78
|
2 |
|
$number = intval($this->load($key)) + $step; |
79
|
|
|
} else { |
80
|
1 |
|
$number = 1; |
81
|
|
|
} |
82
|
2 |
|
return $this->save($key, strval($number)); |
83
|
|
|
} |
84
|
|
|
|
85
|
2 |
|
public function decrement(string $key, int $step = 1): bool |
86
|
|
|
{ |
87
|
2 |
|
if ($this->exists($key)) { |
88
|
2 |
|
$number = intval($this->load($key)) - $step; |
89
|
|
|
} else { |
90
|
1 |
|
$number = 0; |
91
|
|
|
} |
92
|
2 |
|
return $this->save($key, strval($number)); |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
|