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