7
7
use Psr \Cache \CacheItemPoolInterface ;
8
8
use Psr \Http \Message \RequestInterface ;
9
9
use Psr \Http \Message \ResponseInterface ;
10
+ use Symfony \Component \OptionsResolver \OptionsResolver ;
10
11
11
12
/**
12
13
* Allow for caching a response.
@@ -25,32 +26,22 @@ class CachePlugin implements Plugin
25
26
*/
26
27
private $ streamFactory ;
27
28
28
- /**
29
- * Default time to store object in cache. This value is used if CachePlugin::respectCacheHeaders is false or
30
- * if cache headers are missing.
31
- *
32
- * @var int
33
- */
34
- private $ defaultTtl ;
35
-
36
- /**
37
- * Look at the cache headers to know how long this response is going to be cached.
38
- *
39
- * @var bool
40
- */
41
- private $ respectCacheHeaders ;
29
+ private $ config = [
30
+ 'default_ttl ' => null ,
31
+ 'respect_cache_headers ' => true
32
+ ];
42
33
43
34
/**
44
35
* @param CacheItemPoolInterface $pool
45
36
* @param StreamFactory $streamFactory
46
- * @param array $options
37
+ * @param array $config
47
38
*/
48
- public function __construct (CacheItemPoolInterface $ pool , StreamFactory $ streamFactory , array $ options = [])
39
+ public function __construct (CacheItemPoolInterface $ pool , StreamFactory $ streamFactory , array $ config = [])
49
40
{
50
41
$ this ->pool = $ pool ;
51
42
$ this ->streamFactory = $ streamFactory ;
52
- $ this -> defaultTtl = isset ( $ options [ ' default_ttl ' ]) ? $ options [ ' default_ttl ' ] : null ;
53
- $ this ->respectCacheHeaders = isset ( $ options [ ' respect_cache_headers ' ]) ? $ options [ ' respect_cache_headers ' ] : true ;
43
+
44
+ $ this ->config = $ this -> configure ( $ config ) ;
54
45
}
55
46
56
47
/**
@@ -151,8 +142,8 @@ private function createCacheKey(RequestInterface $request)
151
142
*/
152
143
private function getMaxAge (ResponseInterface $ response )
153
144
{
154
- if (!$ this ->respectCacheHeaders ) {
155
- return $ this ->defaultTtl ;
145
+ if (!$ this ->config [ ' respect_cache_headers ' ] ) {
146
+ return $ this ->config [ ' default_ttl ' ] ;
156
147
}
157
148
158
149
// check for max age in the Cache-Control header
@@ -172,6 +163,22 @@ private function getMaxAge(ResponseInterface $response)
172
163
return (new \DateTime ($ header ))->getTimestamp () - (new \DateTime ())->getTimestamp ();
173
164
}
174
165
175
- return $ this ->defaultTtl ;
166
+ return $ this ->config ['default_ttl ' ];
167
+ }
168
+
169
+ /**
170
+ * @param array $config
171
+ *
172
+ * @return array
173
+ */
174
+ protected function configure (array $ config = [])
175
+ {
176
+ $ resolver = new OptionsResolver ();
177
+ $ resolver ->setDefaults ($ this ->config );
178
+
179
+ $ resolver ->setAllowedTypes ('default_ttl ' , 'int ' );
180
+ $ resolver ->setAllowedTypes ('respect_cache_headers ' , 'bool ' );
181
+
182
+ return $ resolver ->resolve ($ config );
176
183
}
177
184
}
0 commit comments