1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\ResponseCache\Middlewares; |
4
|
|
|
|
5
|
|
|
use Closure; |
6
|
|
|
use Illuminate\Http\Request; |
7
|
|
|
use Spatie\ResponseCache\ResponseCache; |
8
|
|
|
use Spatie\ResponseCache\Events\CacheMissed; |
9
|
|
|
use Symfony\Component\HttpFoundation\Response; |
10
|
|
|
use Spatie\ResponseCache\Events\ResponseCacheHit; |
11
|
|
|
use Spatie\ResponseCache\CacheProfiles\CacheProfile; |
12
|
|
|
|
13
|
|
|
class CacheResponse |
14
|
|
|
{ |
15
|
|
|
/** @var \Spatie\ResponseCache\ResponseCache */ |
16
|
|
|
protected $responseCache; |
17
|
|
|
|
18
|
|
|
/** @var \Spatie\ResponseCache\CacheProfiles\CacheProfile */ |
19
|
|
|
protected $cacheProfile; |
20
|
|
|
|
21
|
|
|
public function __construct(ResponseCache $responseCache, CacheProfile $cacheProfile) |
22
|
|
|
{ |
23
|
|
|
$this->responseCache = $responseCache; |
24
|
|
|
$this->cacheProfile = $cacheProfile; |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
public function handle(Request $request, Closure $next, $lifetimeInSeconds = null): Response |
28
|
|
|
{ |
29
|
|
|
if ($this->responseCache->enabled($request)) { |
30
|
|
|
if ($this->responseCache->hasBeenCached($request)) { |
31
|
|
|
event(new ResponseCacheHit($request)); |
32
|
|
|
|
33
|
|
|
$response = $this->responseCache->getCachedResponseFor($request); |
34
|
|
|
|
35
|
|
|
if ($response->getContent()) { |
36
|
|
|
foreach (config('responsecache.replacers', []) as $replacerClass) { |
37
|
|
|
$replacer = resolve($replacerClass); |
38
|
|
|
if ($replacer instanceof \Spatie\ResponseCache\Replacers\ReplacerInterface) { |
39
|
|
|
$cachedValue = $this->responseCache->getCachedKeyFor($request, $replacer->getKey()); |
40
|
|
|
$response->setContent(str_replace($cachedValue, $replacer->getValue(), $response->getContent())); |
41
|
|
|
} |
42
|
|
|
} |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
return $response; |
46
|
|
|
} |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
$response = $next($request); |
50
|
|
|
|
51
|
|
|
if ($this->responseCache->enabled($request)) { |
52
|
|
|
if ($this->responseCache->shouldCache($request, $response)) { |
53
|
|
|
$this->responseCache->cacheResponse($request, $response, $lifetimeInSeconds); |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
event(new CacheMissed($request)); |
58
|
|
|
|
59
|
|
|
return $response; |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|