1
+ <?php
2
+ /**
3
+ * Created by PhpStorm.
4
+ * User: Geolim4
5
+ * Date: 12/05/2018
6
+ * Time: 02:18
7
+ */
8
+
9
+ namespace Phpfastcache \Bundle \Response ;
10
+
11
+ use Phpfastcache \Core \Pool \ExtendedCacheItemPoolInterface ;
12
+ use Phpfastcache \Exceptions \PhpfastcacheLogicException ;
13
+ use Symfony \Component \HttpFoundation \Request ;
14
+ use Symfony \Component \HttpFoundation \Response ;
15
+
16
+ class CacheableResponse
17
+ {
18
+ const RESPONSE_PREFIX = '__CACH_RESP__ ' ;
19
+
20
+ /**
21
+ * @var ExtendedCacheItemPoolInterface
22
+ */
23
+ protected $ request ;
24
+
25
+ /**
26
+ * @var ExtendedCacheItemPoolInterface
27
+ */
28
+ protected $ cacheInstance ;
29
+
30
+ /**
31
+ * CachePromise constructor.
32
+ * @param ExtendedCacheItemPoolInterface $cacheInstance
33
+ */
34
+ public function __construct (ExtendedCacheItemPoolInterface $ cacheInstance , Request $ request )
35
+ {
36
+ $ this ->cacheInstance = $ cacheInstance ;
37
+ $ this ->request = $ request ;
38
+ }
39
+
40
+ /**
41
+ * @param string $cacheKey
42
+ * @param int|\DateInterval $expiresAfter
43
+ * @param callable $callback
44
+ * @return mixed
45
+ * @throws PhpfastcacheLogicException
46
+ */
47
+ public function getResponse (string $ cacheKey , $ expiresAfter = null , callable $ callback ): Response
48
+ {
49
+ $ cacheKey = self ::RESPONSE_PREFIX . $ cacheKey ;
50
+ $ cacheItem = $ this ->cacheInstance ->getItem ($ cacheKey );
51
+ $ cacheResponse = $ cacheItem ->get ();
52
+
53
+ /**
54
+ * No isHit() test here as we directly
55
+ * test if the cached response object
56
+ * is effectively a "Response" object
57
+ */
58
+ if (!($ cacheResponse instanceof Response)) {
59
+ $ response = $ callback ();
60
+ if ($ response instanceof Response){
61
+ $ cacheItem ->expiresAfter ($ expiresAfter );
62
+
63
+ $ response ->setExpires ($ cacheItem ->getExpirationDate ());
64
+ $ response ->setSharedMaxAge ($ cacheItem ->getTtl ());
65
+ $ response ->headers ->addCacheControlDirective ('must-revalidate ' , true );
66
+ $ response ->setEtag (md5 ($ response ->getContent ()));
67
+ $ response ->setPublic ();
68
+
69
+ $ cacheItem ->set ($ response );
70
+ $ this ->cacheInstance ->save ($ cacheItem );
71
+ $ cacheResponse = $ response ;
72
+ }else {
73
+ throw new PhpfastcacheLogicException ('Your callback response MUST return a valid Symfony HTTP Foundation Response object ' );
74
+ }
75
+ }else {
76
+ $ cacheResponse ->isNotModified ($ this ->request );
77
+ }
78
+
79
+ return $ cacheResponse ;
80
+ }
81
+ }
0 commit comments