1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\ResponseCache\Middlewares; |
4
|
|
|
|
5
|
|
|
use Closure; |
6
|
|
|
use Illuminate\Http\Request; |
7
|
|
|
use Spatie\ResponseCache\Replacers\Replacer; |
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
|
|
|
collect(config('responsecache.replacers', []))->map(function ($replacerClass) { |
38
|
|
|
return resolve($replacerClass); |
39
|
|
|
})->each(function (Replacer $replacer) use ($request, $response) { |
40
|
|
|
$cachedValue = $this->responseCache->getCachedKeyFor($request, $replacer->searchFor()); |
41
|
|
|
$response->setContent(str_replace($cachedValue, $replacer->replaceBy(), $response->getContent())); |
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
|
|
|
|