33namespace ByJG \Cache \Psr16 ;
44
55use ByJG \Cache \Exception \InvalidArgumentException ;
6+ use ByJG \Cache \GarbageCollectorInterface ;
67use DateInterval ;
78use Psr \Container \ContainerExceptionInterface ;
89use Psr \Container \NotFoundExceptionInterface ;
910use Psr \Log \LoggerInterface ;
1011use Psr \Log \NullLogger ;
1112
12- class ArrayCacheEngine extends BaseCacheEngine
13+ class ArrayCacheEngine extends BaseCacheEngine implements GarbageCollectorInterface
1314{
1415
15- protected array $ cache = [];
16+ protected array $ cache = [
17+ "ttl " => []
18+ ];
1619
1720 protected LoggerInterface |null $ logger = null ;
1821
@@ -41,7 +44,7 @@ public function has(string $key): bool
4144 {
4245 $ key = $ this ->getKeyFromContainer ($ key );
4346 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 " ]) {
4548 $ this ->delete ($ key );
4649 return false ;
4750 }
@@ -93,7 +96,7 @@ public function set(string $key, mixed $value, DateInterval|int|null $ttl = null
9396
9497 $ this ->cache [$ key ] = serialize ($ value );
9598 if (!empty ($ ttl )) {
96- $ this ->cache ["$ key.ttl " ] = $ this ->addToNow ($ ttl );
99+ $ this ->cache ["ttl " ][ " $ key " ] = $ this ->addToNow ($ ttl );
97100 }
98101
99102 return true ;
@@ -116,12 +119,32 @@ public function delete(string $key): bool
116119 $ key = $ this ->getKeyFromContainer ($ key );
117120
118121 unset($ this ->cache [$ key ]);
119- unset($ this ->cache ["$ key.ttl " ]);
122+ unset($ this ->cache ["ttl " ][ " $ key " ]);
120123 return true ;
121124 }
122125
123126 public function isAvailable (): bool
124127 {
125128 return true ;
126129 }
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+ }
127150}
0 commit comments