-
-
Notifications
You must be signed in to change notification settings - Fork 540
/
Cache.php
76 lines (61 loc) · 1.76 KB
/
Cache.php
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
<?php
namespace Statamic\StaticCaching\Middleware;
use Closure;
use Statamic\Statamic;
use Statamic\StaticCaching\Cacher;
class Cache
{
/**
* @var Cacher
*/
private $cacher;
public function __construct(Cacher $cacher)
{
$this->cacher = $cacher;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($this->canBeCached($request) && ($cached = $this->cacher->getCachedPage($request))) {
return response($cached);
}
$response = $next($request);
if ($this->shouldBeCached($request, $response)) {
$this->cacher->cachePage($request, $response);
}
return $response;
}
private function canBeCached($request)
{
if ($request->method() !== 'GET') {
return false;
}
if (Statamic::isCpRoute()) {
return false;
}
return true;
}
private function shouldBeCached($request, $response)
{
// Only GET requests should be cached. For instance, Live Preview hits frontend URLs as
// POST requests to preview the changes. We don't want those to trigger any caching,
// or else pending changes will be shown immediately, even without hitting save.
if ($request->method() !== 'GET') {
return false;
}
// Draft pages should not be cached.
if ($response->headers->has('X-Statamic-Draft')) {
return false;
}
if ($response->getStatusCode() !== 200 || $response->getContent() == '') {
return false;
}
return true;
}
}