3
3
namespace ByJG \Cache \Psr16 ;
4
4
5
5
use ByJG \Cache \Exception \InvalidArgumentException ;
6
+ use ByJG \Cache \GarbageCollectorInterface ;
6
7
use DateInterval ;
7
8
use Psr \Container \ContainerExceptionInterface ;
8
9
use Psr \Container \NotFoundExceptionInterface ;
9
10
use Psr \Log \LoggerInterface ;
10
11
use Psr \Log \NullLogger ;
11
12
12
- class ArrayCacheEngine extends BaseCacheEngine
13
+ class ArrayCacheEngine extends BaseCacheEngine implements GarbageCollectorInterface
13
14
{
14
15
15
- protected array $ cache = [];
16
+ protected array $ cache = [
17
+ "ttl " => []
18
+ ];
16
19
17
20
protected LoggerInterface |null $ logger = null ;
18
21
@@ -41,7 +44,7 @@ public function has(string $key): bool
41
44
{
42
45
$ key = $ this ->getKeyFromContainer ($ key );
43
46
if (isset ($ this ->cache [$ key ])) {
44
- if (isset ($ this ->cache ["$ key.ttl " ]) && time () >= $ this ->cache ["$ key.ttl " ]) {
47
+ if (isset ($ this ->cache [' ttl ' ][ "$ key " ]) && time () >= $ this ->cache ["ttl " ][ " $ key " ]) {
45
48
$ this ->delete ($ key );
46
49
return false ;
47
50
}
@@ -93,7 +96,7 @@ public function set(string $key, mixed $value, DateInterval|int|null $ttl = null
93
96
94
97
$ this ->cache [$ key ] = serialize ($ value );
95
98
if (!empty ($ ttl )) {
96
- $ this ->cache ["$ key.ttl " ] = $ this ->addToNow ($ ttl );
99
+ $ this ->cache ["ttl " ][ " $ key " ] = $ this ->addToNow ($ ttl );
97
100
}
98
101
99
102
return true ;
@@ -116,12 +119,32 @@ public function delete(string $key): bool
116
119
$ key = $ this ->getKeyFromContainer ($ key );
117
120
118
121
unset($ this ->cache [$ key ]);
119
- unset($ this ->cache ["$ key.ttl " ]);
122
+ unset($ this ->cache ["ttl " ][ " $ key " ]);
120
123
return true ;
121
124
}
122
125
123
126
public function isAvailable (): bool
124
127
{
125
128
return true ;
126
129
}
130
+
131
+ public function collectGarbage ()
132
+ {
133
+ foreach ($ this ->cache ["ttl " ] as $ key => $ ttl ) {
134
+ if (time () >= $ ttl ) {
135
+ unset($ this ->cache [$ key ]);
136
+ unset($ this ->cache ["ttl " ]["$ key " ]);
137
+ }
138
+ }
139
+ }
140
+
141
+ public function getTtl (string $ key ): ?int
142
+ {
143
+ $ key = $ this ->getKeyFromContainer ($ key );
144
+ if (isset ($ this ->cache ["ttl " ]["$ key " ])) {
145
+ return $ this ->cache ["ttl " ]["$ key " ];
146
+ }
147
+
148
+ return null ;
149
+ }
127
150
}
0 commit comments