|
1
|
|
|
<?php |
|
2
|
|
|
// +---------------------------------------------------------------------- |
|
|
|
|
|
|
3
|
|
|
// | ThinkPHP [ WE CAN DO IT JUST THINK ] |
|
4
|
|
|
// +---------------------------------------------------------------------- |
|
5
|
|
|
// | Copyright (c) 2006~2019 http://thinkphp.cn All rights reserved. |
|
6
|
|
|
// +---------------------------------------------------------------------- |
|
7
|
|
|
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 ) |
|
8
|
|
|
// +---------------------------------------------------------------------- |
|
9
|
|
|
// | Author: liu21st <[email protected]> |
|
10
|
|
|
// +---------------------------------------------------------------------- |
|
11
|
|
|
declare (strict_types = 1); |
|
12
|
|
|
|
|
13
|
|
|
namespace think\middleware; |
|
14
|
|
|
|
|
15
|
|
|
use Closure; |
|
16
|
|
|
use think\Cache; |
|
17
|
|
|
use think\Request; |
|
18
|
|
|
use think\Response; |
|
19
|
|
|
|
|
20
|
|
|
class CheckRequestCache |
|
|
|
|
|
|
21
|
|
|
{ |
|
22
|
|
|
protected $cache; |
|
23
|
|
|
|
|
24
|
|
|
public function __construct(Cache $cache) |
|
|
|
|
|
|
25
|
|
|
{ |
|
26
|
|
|
$this->cache = $cache; |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
/** |
|
|
|
|
|
|
30
|
|
|
* 设置当前地址的请求缓存 |
|
31
|
|
|
* @access public |
|
32
|
|
|
* @param Request $request |
|
|
|
|
|
|
33
|
|
|
* @param $next |
|
|
|
|
|
|
34
|
|
|
* @return Response |
|
35
|
|
|
*/ |
|
36
|
|
|
public function handle($request, Closure $next) |
|
37
|
|
|
{ |
|
38
|
|
|
$cache = $request->cache(); |
|
39
|
|
|
|
|
40
|
|
|
if ($cache) { |
|
41
|
|
|
list($key, $expire, $tag) = $cache; |
|
42
|
|
|
|
|
43
|
|
|
if (strtotime($request->server('HTTP_IF_MODIFIED_SINCE')) + $expire > $request->server('REQUEST_TIME')) { |
|
44
|
|
|
// 读取缓存 |
|
45
|
|
|
return Response::create()->code(304); |
|
46
|
|
|
} elseif ($this->cache->has($key)) { |
|
47
|
|
|
list($content, $header) = $this->cache->get($key); |
|
48
|
|
|
|
|
49
|
|
|
return Response::create($content)->header($header); |
|
50
|
|
|
} |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
$response = $next($request); |
|
54
|
|
|
|
|
55
|
|
|
if (200 == $response->getCode() && $response->isAllowCache()) { |
|
56
|
|
|
if ($cache) { |
|
57
|
|
|
$header = $response->getHeader(); |
|
58
|
|
|
$header['Cache-Control'] = 'max-age=' . $expire . ',must-revalidate'; |
|
|
|
|
|
|
59
|
|
|
$header['Last-Modified'] = gmdate('D, d M Y H:i:s') . ' GMT'; |
|
60
|
|
|
$header['Expires'] = gmdate('D, d M Y H:i:s', time() + $expire) . ' GMT'; |
|
61
|
|
|
|
|
62
|
|
|
$this->cache->tag($tag)->set($key, [$response->getContent(), $header], $expire); |
|
|
|
|
|
|
63
|
|
|
} |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
return $response; |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|