SetCacheHeaders.php
1.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php
namespace Illuminate\Http\Middleware;
use Closure;
use Illuminate\Support\Carbon;
class SetCacheHeaders
{
/**
* Add cache related HTTP headers.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|array $options
* @return \Symfony\Component\HttpFoundation\Response
*
* @throws \InvalidArgumentException
*/
public function handle($request, Closure $next, $options = [])
{
$response = $next($request);
if (! $request->isMethodCacheable() || ! $response->getContent()) {
return $response;
}
if (is_string($options)) {
$options = $this->parseOptions($options);
}
if (isset($options['etag']) && $options['etag'] === true) {
$options['etag'] = md5($response->getContent());
}
if (isset($options['last_modified'])) {
if (is_numeric($options['last_modified'])) {
$options['last_modified'] = Carbon::createFromTimestamp($options['last_modified']);
} else {
$options['last_modified'] = Carbon::parse($options['last_modified']);
}
}
$response->setCache($options);
$response->isNotModified($request);
return $response;
}
/**
* Parse the given header options.
*
* @param string $options
* @return array
*/
protected function parseOptions($options)
{
return collect(explode(';', rtrim($options, ';')))->mapWithKeys(function ($option) {
$data = explode('=', $option, 2);
return [$data[0] => $data[1] ?? true];
})->all();
}
}