chengkun
2025-06-05 4080b5997b38ca84b3b203c7101dcadb97b76925
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2025 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
declare(strict_types=1);
 
namespace think\middleware;
 
use Closure;
use think\Cache;
use think\Config;
use think\Request;
use think\Response;
 
/**
 * 请求缓存处理
 */
class CheckRequestCache
{
    /**
     * 缓存对象
     * @var Cache
     */
    protected $cache;
 
    /**
     * 配置参数
     * @var array
     */
    protected $config = [
        // 请求缓存规则 true为自动规则
        'request_cache_key'    => true,
        // 请求缓存有效期
        'request_cache_expire' => null,
        // 全局请求缓存排除规则
        'request_cache_except' => [],
        // 请求缓存的Tag
        'request_cache_tag'    => '',
    ];
 
    public function __construct(Cache $cache, Config $config)
    {
        $this->cache  = $cache;
        $this->config = array_merge($this->config, $config->get('route'));
    }
 
    /**
     * 设置当前地址的请求缓存
     * @access public
     * @param Request $request
     * @param Closure $next
     * @param mixed   $cache
     * @return Response
     */
    public function handle(Request $request, Closure $next, $cache = null): Response
    {
        if ($request->isGet() && false !== $cache) {
            if (false === $this->config['request_cache_key']) {
                // 关闭当前缓存
                $cache = false;
            }
 
            $cache = $cache ?? $this->getRequestCache($request);
 
            if ($cache) {
                if (is_array($cache)) {
                    [$key, $expire, $tag] = array_pad($cache, 3, '');
                } else {
                    $key    = md5($request->url(true));
                    $expire = $cache;
                    $tag    = '';
                }
 
                $key = $this->parseCacheKey($request, $key);
 
                if (strtotime($request->server('HTTP_IF_MODIFIED_SINCE', '')) + $expire > $request->server('REQUEST_TIME')) {
                    // 读取缓存
                    return Response::create()->code(304);
                } elseif (($hit = $this->cache->get($key)) !== null) {
                    [$content, $header, $when] = $hit;
                    if (null === $expire || $when + $expire > $request->server('REQUEST_TIME')) {
                        return Response::create($content)->header($header);
                    }
                }
            }
        }
 
        $response = $next($request);
 
        if (isset($key) && 200 == $response->getCode() && $response->isAllowCache()) {
            $header                  = $response->getHeader();
            $header['Cache-Control'] = 'max-age=' . $expire . ',must-revalidate';
            $header['Last-Modified'] = gmdate('D, d M Y H:i:s') . ' GMT';
            $header['Expires']       = gmdate('D, d M Y H:i:s', time() + $expire) . ' GMT';
 
            $this->cache->tag($tag)->set($key, [$response->getContent(), $header, time()], $expire);
        }
 
        return $response;
    }
 
    /**
     * 读取当前地址的请求缓存信息
     * @access protected
     * @param Request $request
     * @return mixed
     */
    protected function getRequestCache($request)
    {
        $key    = $this->config['request_cache_key'];
        $expire = $this->config['request_cache_expire'];
        $except = $this->config['request_cache_except'];
        $tag    = $this->config['request_cache_tag'];
 
        foreach ($except as $rule) {
            if (0 === stripos($request->url(), $rule)) {
                return;
            }
        }
 
        return [$key, $expire, $tag];
    }
 
    /**
     * 读取当前地址的请求缓存信息
     * @access protected
     * @param Request $request
     * @param mixed   $key
     * @return null|string
     */
    protected function parseCacheKey($request, $key)
    {
        if ($key instanceof Closure) {
            $key = call_user_func($key, $request);
        }
 
        if (false === $key) {
            // 关闭当前缓存
            return;
        }
 
        if (true === $key) {
            // 自动缓存功能
            $key = '__URL__';
        } elseif (str_contains($key, '|')) {
            [$key, $fun] = explode('|', $key);
        }
 
        // 特殊规则替换
        if (str_contains($key, '__')) {
            $key = str_replace(['__CONTROLLER__', '__ACTION__', '__URL__'], [$request->controller(), $request->action(), md5($request->url(true))], $key);
        }
 
        if (str_contains($key, ':')) {
            $param = $request->param();
 
            foreach ($param as $item => $val) {
                if (is_string($val) && str_contains($key, ':' . $item)) {
                    $key = str_replace(':' . $item, (string) $val, $key);
                }
            }
        } elseif (str_contains($key, ']')) {
            if ('[' . $request->ext() . ']' == $key) {
                // 缓存某个后缀的请求
                $key = md5($request->url());
            } else {
                return;
            }
        }
 
        if (isset($fun)) {
            $key = $fun($key);
        }
 
        return $key;
    }
}