1 | <?php |
||
14 | class CacheResponse |
||
15 | { |
||
16 | protected ResponseCache $responseCache; |
||
|
|||
17 | |||
18 | public function __construct(ResponseCache $responseCache) |
||
19 | { |
||
20 | $this->responseCache = $responseCache; |
||
21 | } |
||
22 | |||
23 | public function handle(Request $request, Closure $next, ...$args): Response |
||
24 | { |
||
25 | $lifetimeInSeconds = $this->getLifetime($args); |
||
26 | $tags = $this->getTags($args); |
||
27 | |||
28 | if ($this->responseCache->enabled($request)) { |
||
29 | if ($this->responseCache->hasBeenCached($request, $tags)) { |
||
30 | event(new ResponseCacheHit($request)); |
||
31 | |||
32 | $response = $this->responseCache->getCachedResponseFor($request, $tags); |
||
33 | |||
34 | $this->getReplacers()->each(function (Replacer $replacer) use ($response) { |
||
35 | $replacer->replaceInCachedResponse($response); |
||
36 | }); |
||
37 | |||
38 | return $response; |
||
39 | } |
||
40 | } |
||
41 | |||
42 | $response = $next($request); |
||
43 | |||
44 | if ($this->responseCache->enabled($request)) { |
||
45 | if ($this->responseCache->shouldCache($request, $response)) { |
||
46 | $this->makeReplacementsAndCacheResponse($request, $response, $lifetimeInSeconds, $tags); |
||
47 | } |
||
48 | } |
||
49 | |||
50 | event(new CacheMissed($request)); |
||
51 | |||
52 | return $response; |
||
53 | } |
||
54 | |||
55 | protected function makeReplacementsAndCacheResponse( |
||
56 | Request $request, |
||
57 | Response $response, |
||
58 | ?int $lifetimeInSeconds = null, |
||
59 | array $tags = [] |
||
60 | ): void { |
||
61 | $cachedResponse = clone $response; |
||
62 | |||
63 | $this->getReplacers()->each(function (Replacer $replacer) use ($cachedResponse) { |
||
64 | $replacer->prepareResponseToCache($cachedResponse); |
||
65 | }); |
||
66 | |||
67 | $this->responseCache->cacheResponse($request, $cachedResponse, $lifetimeInSeconds, $tags); |
||
68 | } |
||
69 | |||
70 | protected function getReplacers(): Collection |
||
71 | { |
||
72 | return collect(config('responsecache.replacers')) |
||
73 | ->map(function (string $replacerClass) { |
||
74 | return app($replacerClass); |
||
75 | }); |
||
76 | } |
||
77 | |||
78 | protected function getLifetime(array $args): ?int |
||
79 | { |
||
80 | if (count($args) >= 1 && is_numeric($args[0])) { |
||
81 | return (int) $args[0]; |
||
82 | } |
||
83 | |||
84 | return null; |
||
85 | } |
||
86 | |||
87 | protected function getTags(array $args): array |
||
88 | { |
||
89 | $tags = $args; |
||
90 | |||
91 | if (count($args) >= 1 && is_numeric($args[0])) { |
||
92 | $tags = array_slice($args, 1); |
||
93 | } |
||
94 | |||
95 | return array_filter($tags); |
||
96 | } |
||
97 | } |
||
98 |