1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\ResponseCache; |
4
|
|
|
|
5
|
|
|
use Illuminate\Cache\Repository; |
6
|
|
|
use Illuminate\Cache\TaggedCache; |
7
|
|
|
use Spatie\ResponseCache\Serializers\Serializer; |
8
|
|
|
use Symfony\Component\HttpFoundation\Response; |
9
|
|
|
|
10
|
|
|
class ResponseCacheRepository |
11
|
|
|
{ |
12
|
|
|
protected Repository $cache; |
|
|
|
|
13
|
|
|
|
14
|
|
|
protected Serializer $responseSerializer; |
15
|
|
|
|
16
|
|
|
public function __construct(Serializer $responseSerializer, Repository $cache) |
17
|
|
|
{ |
18
|
|
|
$this->cache = $cache; |
19
|
|
|
|
20
|
|
|
$this->responseSerializer = $responseSerializer; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* @param string $key |
25
|
|
|
* @param \Symfony\Component\HttpFoundation\Response $response |
26
|
|
|
* @param \DateTime|int $seconds |
27
|
|
|
*/ |
28
|
|
|
public function put(string $key, $response, $seconds) |
29
|
|
|
{ |
30
|
|
|
$this->cache->put($key, $this->responseSerializer->serialize($response), is_numeric($seconds) ? now()->addSeconds($seconds) : $seconds); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function has(string $key): bool |
34
|
|
|
{ |
35
|
|
|
return $this->cache->has($key); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function get(string $key): Response |
39
|
|
|
{ |
40
|
|
|
return $this->responseSerializer->unserialize($this->cache->get($key)); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
public function clear(): void |
44
|
|
|
{ |
45
|
|
|
if ($this->isTagged($this->cache)) { |
46
|
|
|
$this->cache->clear(); |
47
|
|
|
|
48
|
|
|
return; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
if (empty(config('responsecache.cache_tag'))) { |
52
|
|
|
$this->cache->clear(); |
53
|
|
|
|
54
|
|
|
return; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
$this->cache->tags(config('responsecache.cache_tag'))->flush(); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
public function forget(string $key): bool |
61
|
|
|
{ |
62
|
|
|
return $this->cache->forget($key); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
public function tags(array $tags): self |
66
|
|
|
{ |
67
|
|
|
return new self($this->responseSerializer, $this->cache->tags($tags)); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
public function isTagged($repository): bool |
71
|
|
|
{ |
72
|
|
|
return $repository instanceof TaggedCache && ! empty($repository->getTags()); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|