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