@@ -23,6 +23,7 @@ class Unleash
23
23
protected $ config ;
24
24
protected $ request ;
25
25
protected $ features ;
26
+ protected $ expires ;
26
27
27
28
public function __construct (ClientInterface $ client , Cache $ cache , Config $ config , Request $ request )
28
29
{
@@ -34,13 +35,17 @@ public function __construct(ClientInterface $client, Cache $cache, Config $confi
34
35
35
36
public function getFeatures (): array
36
37
{
38
+ if ($ this ->isFresh ()) {
39
+ return $ this ->features ;
40
+ }
41
+
37
42
try {
38
- $ features = $ this ->getCachedFeatures ();
43
+ $ this -> features = $ this ->getCachedFeatures ();
39
44
40
45
// Always store the failover cache, in case it is turned on during failure scenarios.
41
- $ this ->cache ->forever ('unleash.features.failover ' , $ features );
46
+ $ this ->cache ->forever ('unleash.features.failover ' , $ this -> features );
42
47
43
- return $ features ;
48
+ return $ this -> features ;
44
49
} catch (TransferException | JsonException $ e ) {
45
50
if ($ this ->config ->get ('unleash.cache.failover ' ) === true ) {
46
51
return $ this ->cache ->get ('unleash.features.failover ' , []);
@@ -110,16 +115,23 @@ public function isFeatureDisabled(string $name, ...$args): bool
110
115
return !$ this ->isFeatureEnabled ($ name , ...$ args );
111
116
}
112
117
118
+ protected function isFresh (): bool
119
+ {
120
+ return $ this ->expires > time ();
121
+ }
122
+
113
123
protected function getCachedFeatures (): array
114
124
{
115
125
if (!$ this ->config ->get ('unleash.isEnabled ' )) {
116
126
return [];
117
127
}
118
128
119
129
if ($ this ->config ->get ('unleash.cache.isEnabled ' )) {
130
+ $ this ->setExpires ();
131
+
120
132
return $ this ->cache ->remember (
121
133
'unleash ' ,
122
- $ this ->config -> get ( ' unleash.cache.ttl ' , self :: DEFAULT_CACHE_TTL ),
134
+ $ this ->getCacheTTL ( ),
123
135
function () {
124
136
return $ this ->fetchFeatures ();
125
137
}
@@ -129,6 +141,16 @@ function () {
129
141
return $ this ->features ?? $ this ->features = $ this ->fetchFeatures ();
130
142
}
131
143
144
+ protected function getCacheTTL (): int
145
+ {
146
+ return $ this ->config ->get ('unleash.cache.ttl ' , self ::DEFAULT_CACHE_TTL );
147
+ }
148
+
149
+ protected function setExpires (): void
150
+ {
151
+ $ this ->expires = $ this ->getCacheTTL () + time ();
152
+ }
153
+
132
154
protected function fetchFeatures (): array
133
155
{
134
156
$ response = $ this ->client ->get ($ this ->config ->get ('unleash.featuresEndpoint ' ));
@@ -139,6 +161,8 @@ protected function fetchFeatures(): array
139
161
throw new JsonException ('Could not decode unleash response body. ' , $ e ->getCode (), $ e );
140
162
}
141
163
164
+ $ this ->setExpires ();
165
+
142
166
return $ this ->formatResponse ($ data );
143
167
}
144
168
0 commit comments