-
-
Notifications
You must be signed in to change notification settings - Fork 621
Expand file tree
/
Copy pathDefaultCache.php
More file actions
120 lines (95 loc) · 3.03 KB
/
DefaultCache.php
File metadata and controls
120 lines (95 loc) · 3.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
<?php
namespace Statamic\GraphQL\ResponseCache;
use GraphQL\Language\AST\FieldNode;
use GraphQL\Language\Parser;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Cache;
use Statamic\Contracts\GraphQL\ResponseCache;
use Statamic\Events\Event;
class DefaultCache implements ResponseCache
{
public function get(Request $request)
{
if ($this->shouldBypassCache($request->input('query'))) {
return null;
}
return Cache::get($this->getCacheKey($request));
}
public function put(Request $request, $response)
{
$key = $this->track($request);
$ttl = Carbon::now()->addMinutes((int) config('statamic.graphql.cache.expiry', 60));
Cache::put($key, $response, $ttl);
}
protected function track($request)
{
$newKey = $this->getCacheKey($request);
$keys = $this
->getTrackedResponses()
->push($newKey)
->unique()
->values()
->all();
Cache::put($this->getTrackingKey(), $keys);
return $newKey;
}
protected function getTrackedResponses()
{
return collect(Cache::get($this->getTrackingKey(), []));
}
protected function getTrackingKey()
{
return 'gql-cache:tracked-responses';
}
protected function getCacheKey(Request $request)
{
$query = $request->input('query');
$vars = $request->input('variables');
return 'gql-cache:'.md5($query).'_'.md5(json_encode($vars));
}
public function handleInvalidationEvent(Event $event)
{
$this->getTrackedResponses()->each(function ($key) {
Cache::forget($key);
});
Cache::forget($this->getTrackingKey());
}
public function shouldBypassCache(string $query): bool
{
$excludedQueries = config('statamic.graphql.cache.exclude', []);
if (!$excludedQueries) {
return false;
}
$ast = Parser::parse($query);
foreach ($ast->definitions as $definition) {
if (!isset($definition->selectionSet)) {
continue;
}
foreach (array_keys($excludedQueries) as $excludedQuery) {
foreach ($definition->selectionSet->selections as $selection) {
if ($this->containsFieldRecursive($selection, $excludedQuery)) {
return true;
}
}
}
}
return false;
}
private function containsFieldRecursive($node, string $fieldName): bool
{
if ($node instanceof FieldNode) {
if ($node->name->value === $fieldName) {
return true;
}
if ($node->selectionSet) {
foreach ($node->selectionSet->selections as $selection) {
if ($this->containsFieldRecursive($selection, $fieldName)) {
return true;
}
}
}
}
return false;
}
}