1+ <?php
2+
3+ namespace Koded \Caching ;
4+
5+ use Exception ;
6+ use Koded \Caching \Client \CacheClientFactory ;
7+ use Psr \Cache \{CacheItemInterface , CacheItemPoolInterface };
8+ use Psr \SimpleCache \CacheInterface ;
9+
10+
11+ abstract class CacheItemPool implements CacheItemPoolInterface
12+ {
13+ /** @var CacheInterface */
14+ protected $ client ;
15+
16+ /** @var CacheItemInterface[] */
17+ private $ deferred = [];
18+
19+ abstract public function __construct (CacheClientFactory $ factory , string $ client );
20+
21+ public function __destruct ()
22+ {
23+ unset($ this ->client );
24+ }
25+
26+ public function getItems (array $ keys = []): array
27+ {
28+ $ collection = [];
29+ foreach ($ keys as $ key ) {
30+ $ collection [$ key ] = $ this ->getItem ($ key );
31+ }
32+
33+ return $ collection ;
34+ }
35+
36+ public function getItem ($ key ): CacheItemInterface
37+ {
38+ if (isset ($ this ->deferred [$ key ])) {
39+ return $ this ->deferred [$ key ];
40+ }
41+
42+ try {
43+ return (new class ($ this ->client , $ key ) extends CacheItem
44+ {
45+ })->set ($ this ->client ->get ($ key ));
46+
47+ } catch (Exception $ e ) {
48+ throw ExtendedCacheException::from ($ e );
49+ }
50+ }
51+
52+ public function hasItem ($ key ): bool
53+ {
54+ try {
55+ return $ this ->client ->has ($ key );
56+ } catch (Exception $ e ) {
57+ throw ExtendedCacheException::from ($ e );
58+ }
59+ }
60+
61+ public function clear (): bool
62+ {
63+ if ($ this ->client ->clear ()) {
64+ $ this ->deferred = [];
65+ return true ;
66+ }
67+
68+ return false ;
69+ }
70+
71+ public function deleteItems (array $ keys ): bool
72+ {
73+ $ deleted = 0 ;
74+ foreach ($ keys as $ key ) {
75+ $ this ->deleteItem ($ key ) && ++$ deleted ;
76+ }
77+
78+ return count ($ keys ) === $ deleted ;
79+ }
80+
81+ public function deleteItem ($ key ): bool
82+ {
83+ try {
84+ if ($ this ->client ->delete ($ key )) {
85+ unset($ this ->deferred [$ key ]);
86+ return true ;
87+ }
88+
89+ return false ;
90+
91+ } catch (Exception $ e ) {
92+ throw ExtendedCacheException::from ($ e );
93+ }
94+ }
95+
96+ public function saveDeferred (CacheItemInterface $ item ): bool
97+ {
98+ $ this ->deferred [$ item ->getKey ()] = $ item ;
99+
100+ return true ;
101+ }
102+
103+ public function commit (): bool
104+ {
105+ foreach ($ this ->deferred as $ key => $ item ) {
106+ if (true === $ this ->save ($ item )) {
107+ unset($ this ->deferred [$ key ]);
108+ }
109+ }
110+
111+ return empty ($ this ->deferred );
112+ }
113+
114+ public function save (CacheItemInterface $ item ): bool
115+ {
116+ /** @var CacheItem $item */
117+ $ value = (function () {
118+ return $ this ->value ;
119+ })->bindTo ($ item , $ item );
120+
121+ return $ this ->client ->set ($ item ->getKey (), $ value (), cache_ttl ($ item ->ttl ()));
122+ }
123+ }
0 commit comments