77class ViewCache
88{
99 private bool $ _Enabled ;
10- private string $ _CachePath ;
1110 private int $ _DefaultTtl ;
1211 private ICacheStorage $ _Storage ;
12+ private ?CacheConfig $ _Config ;
1313
1414 /**
1515 * ViewCache constructor
1616 *
1717 * @param ICacheStorage $Storage
1818 * @param bool $Enabled
1919 * @param int $DefaultTtl
20+ * @param CacheConfig|null $Config
2021 */
21- public function __construct ( ICacheStorage $ Storage , bool $ Enabled = true , int $ DefaultTtl = 3600 )
22+ public function __construct ( ICacheStorage $ Storage , bool $ Enabled = true , int $ DefaultTtl = 3600 , ? CacheConfig $ Config = null )
2223 {
2324 $ this ->_Storage = $ Storage ;
2425 $ this ->_Enabled = $ Enabled ;
2526 $ this ->_DefaultTtl = $ DefaultTtl ;
27+ $ this ->_Config = $ Config ;
2628 }
2729
2830 /**
@@ -59,7 +61,15 @@ public function set( string $Key, string $Content, ?int $Ttl = null ): bool
5961
6062 $ Ttl = $ Ttl ?? $ this ->_DefaultTtl ;
6163
62- return $ this ->_Storage ->write ( $ Key , $ Content , $ Ttl );
64+ $ Result = $ this ->_Storage ->write ( $ Key , $ Content , $ Ttl );
65+
66+ // Run garbage collection based on probability
67+ if ( $ Result && $ this ->shouldRunGc () )
68+ {
69+ $ this ->gc ();
70+ }
71+
72+ return $ Result ;
6373 }
6474
6575 /**
@@ -140,6 +150,16 @@ public function setEnabled( bool $Enabled ): void
140150 $ this ->_Enabled = $ Enabled ;
141151 }
142152
153+ /**
154+ * Run garbage collection to remove expired cache entries
155+ *
156+ * @return int Number of entries removed
157+ */
158+ public function gc (): int
159+ {
160+ return $ this ->_Storage ->gc ();
161+ }
162+
143163 /**
144164 * Hash data array for cache key
145165 *
@@ -152,4 +172,37 @@ private function hashData( array $Data ): string
152172
153173 return md5 ( serialize ( $ Data ) );
154174 }
175+
176+ /**
177+ * Check if garbage collection should run
178+ *
179+ * @return bool
180+ */
181+ private function shouldRunGc (): bool
182+ {
183+ if ( !$ this ->_Config )
184+ {
185+ // If no config, use default 1% probability
186+ return mt_rand ( 1 , 100 ) === 1 ;
187+ }
188+
189+ $ Probability = $ this ->_Config ->getGcProbability ();
190+
191+ // If probability is 0, GC is disabled
192+ if ( $ Probability <= 0 )
193+ {
194+ return false ;
195+ }
196+
197+ // If probability is 1 or higher, always run
198+ if ( $ Probability >= 1 )
199+ {
200+ return true ;
201+ }
202+
203+ $ Divisor = $ this ->_Config ->getGcDivisor ();
204+
205+ // Roll the dice
206+ return mt_rand ( 1 , $ Divisor ) <= ( $ Probability * $ Divisor );
207+ }
155208}
0 commit comments