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 Spatie\ResponseCache\Replacers\Replacer; |
10
|
|
|
use Symfony\Component\HttpFoundation\Response; |
11
|
|
|
use Spatie\ResponseCache\Events\ResponseCacheHit; |
12
|
|
|
|
13
|
|
|
class CacheResponse |
14
|
|
|
{ |
15
|
|
|
/** @var \Spatie\ResponseCache\ResponseCache */ |
16
|
|
|
protected $responseCache; |
17
|
|
|
|
18
|
|
|
public function __construct(ResponseCache $responseCache) |
19
|
|
|
{ |
20
|
|
|
$this->responseCache = $responseCache; |
21
|
|
|
} |
22
|
|
|
|
23
|
|
|
public function handle(Request $request, Closure $next, $lifetimeInSeconds = null): Response |
24
|
|
|
{ |
25
|
|
|
if ($this->responseCache->enabled($request)) { |
26
|
|
|
if ($this->responseCache->hasBeenCached($request)) { |
27
|
|
|
event(new ResponseCacheHit($request)); |
28
|
|
|
|
29
|
|
|
$response = $this->responseCache->getCachedResponseFor($request); |
30
|
|
|
|
31
|
|
|
if ($response->getContent()) { |
32
|
|
|
collect(config('responsecache.replacers', []))->map(function ($replacerClass) { |
33
|
|
|
return resolve($replacerClass); |
34
|
|
|
})->each(function (Replacer $replacer) use ($request, $response) { |
35
|
|
|
$cachedValue = $this->responseCache->getCachedKeyFor($request, $replacer->searchFor()); |
36
|
|
|
$response->setContent(str_replace($cachedValue, $replacer->replaceBy(), $response->getContent())); |
37
|
|
|
}); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
return $response; |
41
|
|
|
} |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
$response = $next($request); |
45
|
|
|
|
46
|
|
|
if ($this->responseCache->enabled($request)) { |
47
|
|
|
if ($this->responseCache->shouldCache($request, $response)) { |
48
|
|
|
$this->responseCache->cacheResponse($request, $response, $lifetimeInSeconds); |
49
|
|
|
} |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
event(new CacheMissed($request)); |
53
|
|
|
|
54
|
|
|
return $response; |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|