1212namespace Cache \Adapter \MongoDB ;
1313
1414use Cache \Adapter \Common \AbstractCachePool ;
15+ use Cache \Adapter \Common \CacheItem ;
16+ use MongoDB \BSON \UTCDateTime ;
17+ use MongoDB \Collection ;
18+ use MongoDB \Driver \Manager ;
1519use Psr \Cache \CacheItemInterface ;
16- use MongoDB \Client ;
1720
1821/**
1922 * @author Tobias Nyholm <[email protected] > 2023 */
2124class MongoDBCachePool extends AbstractCachePool
2225{
2326 /**
24- * @var Client
27+ * @type Collection
2528 */
26- private $ client ;
29+ private $ collection ;
2730
2831 /**
29- *
30- * @param Client $client
32+ * @param Collection $collection
3133 */
32- public function __construct (Client $ client )
34+ public function __construct (Collection $ collection )
3335 {
34- $ this ->client = $ client ;
36+ $ this ->collection = $ collection ;
37+ }
38+
39+ public static function createCollection (Manager $ manager , $ namespace )
40+ {
41+ $ collection = new Collection ($ manager , $ namespace );
42+ $ collection ->createIndex (['expireAt ' => 1 ], ['expireAfterSeconds ' => 0 ]);
43+
44+ return $ collection ;
3545 }
3646
3747 protected function fetchObjectFromCache ($ key )
3848 {
49+ $ object = $ this ->collection ->findOne (['_id ' => $ key ]);
50+
51+ if ($ object && isset ($ object ->data )) {
52+ $ item = new CacheItem ($ key , true , unserialize ($ object ->data ));
53+
54+ if (isset ($ object ->expiresAt )) {
55+ $ item ->expiresAt ($ object ->expiresAt ->toDateTime ());
56+ }
57+
58+ return $ item ;
59+ }
60+
3961 return false ;
4062 }
4163
4264 protected function clearAllObjectsFromCache ()
4365 {
66+ $ this ->collection ->deleteMany ([]);
67+
4468 return true ;
4569 }
4670
4771 protected function clearOneObjectFromCache ($ key )
4872 {
73+ $ this ->collection ->deleteOne (['_id ' => $ key ]);
74+
4975 return true ;
5076 }
5177
5278 protected function storeItemInCache ($ key , CacheItemInterface $ item , $ ttl )
5379 {
80+ $ object = [
81+ '_id ' => $ key ,
82+ 'data ' => serialize ($ item ->get ()),
83+ ];
84+
85+ if ($ ttl ) {
86+ $ object ['expiresAt ' ] = new UTCDateTime ((time () + $ ttl ) * 1000 );
87+ }
88+
89+ $ this ->collection ->updateOne (['_id ' => $ key ], ['$set ' => $ object ], ['upsert ' => true ]);
90+
5491 return true ;
5592 }
56- }
93+ }
0 commit comments