chengkun
2025-09-09 774d962b76d63366ed26c395e0a33cdbec309242
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
<?php
 
declare (strict_types=1);
 
namespace app;
 
error_reporting(E_ERROR | E_PARSE);
 
use think\App;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\Response;
use think\Validate;
use think\facade\Request;
use think\facade\View;
use think\facade\Config;
 
/**
 * 控制器基础类
 */
abstract class BaseController {
    
    /**
     * Request实例
     * @var \think\Request
     */
    protected $request;
    
    /**
     * 应用实例
     * @var \think\App
     */
    protected $app;
    
    /**
     * 是否批量验证
     * @var bool
     */
    protected $batchValidate = FALSE;
    
    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [];
    
    /**
     * 构造方法
     * @access public
     * @param App $app 应用对象
     */
    public function __construct(App $app) {
        $this->app = $app;
        $this->request = $this->app->request;
        
        // 控制器初始化
        $this->initialize();
    }
    
    // 初始化
    protected function initialize() {
        
    }
    
    /**
     * 验证数据
     * @access protected
     * @param array $data 数据
     * @param string|array $validate 验证器名或者验证规则数组
     * @param array $message 提示信息
     * @param bool $batch 是否批量验证
     * @return array|string|true
     * @throws ValidateException
     */
    protected function validate(array $data, $validate, array $message = [], bool $batch = FALSE) {
        if (is_array($validate)) {
            $v = new Validate();
            $v->rule($validate);
        } else {
            if (strpos($validate, '.')) {
                // 支持场景
                [$validate, $scene] = explode('.', $validate);
            }
            $class = FALSE !== strpos($validate, '\\') ? $validate : app()->parseClass('validate', $validate);
            $v = new $class();
            if (!empty($scene)) {
                $v->scene($scene);
            }
        }
        
        $v->message($message);
        
        
        // 是否批量验证
        if ($batch || $this->batchValidate) {
            $v->batch(TRUE);
        }
        
        return $v->failException(TRUE)->check($data);
    }
    
    /**
     * 操作成功跳转的快捷方法
     * @access protected
     * @param mixed $msg 提示信息
     * @param string $url 跳转的URL地址
     * @param mixed $data 返回的数据
     * @param integer $wait 跳转等待时间
     * @param array $header 发送的Header信息
     * @return void
     */
    protected function success($msg = '', string $url = NULL, $data = '', int $wait = 3, array $header = []) {
        if (is_null($url) && isset($_SERVER["HTTP_REFERER"])) {
            $url = $_SERVER["HTTP_REFERER"];
        } elseif ($url) {
            $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : (string)app()->route->buildUrl($url);
        }
        
        $result = [
            'code'    => 1,
            'msg'     => $msg,
            'data'    => $data,
            'url'     => $url,
            'wait'    => $wait,
            'message' => $msg,
        ];
        if (!$result['url']) {
            $result['url'] = $_SERVER["HTTP_REFERER"];
        }
        $type = $this->getResponseType();
        // 把跳转模板的渲染下沉,这样在 response_send 行为里通过getData()获得的数据是一致性的格式
        if ('html' == strtolower($type)) {
            $type = 'view';
            $response = Response::create(app()->config->get('jump.dispatch_success_tmpl'), $type)->assign($result)->header($header);
        } else {
            $response = Response::create($result, $type)->header($header);
        }
        
        throw new HttpResponseException($response);
    }
    
    /**
     * 操作错误跳转的快捷方法
     * @access protected
     * @param mixed $msg 提示信息
     * @param string $url 跳转的URL地址
     * @param mixed $data 返回的数据
     * @param integer $wait 跳转等待时间
     * @param array $header 发送的Header信息
     * @return void
     */
    protected function error($msg = '', string $url = NULL, $data = '', int $wait = 3, array $header = []) {
        if (is_null($url)) {
            $url = request::isAjax() ? '' : 'javascript:history.back(-1);';
        } elseif ($url) {
            $url = (strpos($url, '://') || 0 === strpos($url, '/')) ? $url : (string)app()->route->buildUrl($url);
        }
        
        $result = [
            'code'  => 0,
            'msg'   => $msg,
            'data'  => $data,
            'url'   => $url,
            'wait'  => $wait,
            'error' => $msg,
        ];
        if (!$result['url']) {
            $result['url'] = $_SERVER["HTTP_REFERER"];
        }
        $type = $this->getResponseType();
//        pr($result);
//        exit;
        if ('html' == strtolower($type)) {
            $type = 'view';
            $response = Response::create(app()->config->get('jump.dispatch_error_tmpl'), $type)->assign($result)->header($header);
        } else {
            $response = Response::create($result, $type)->header($header);
        }
        
        throw new HttpResponseException($response);
    }
    
    /**
     * 返回封装后的API数据到客户端
     * @access protected
     * @param mixed $data 要返回的数据
     * @param integer $code 返回的code
     * @param mixed $msg 提示信息
     * @param string $type 返回数据格式
     * @param array $header 发送的Header信息
     * @return void
     */
    protected function result($data, $code = 0, $msg = '', $type = 'json', array $header = []) {
        $result = [
            'code' => $code,
            'msg'  => $msg,
            'time' => time(),
            'data' => $data,
        ];
        
        $type = $type ?: $this->getResponseType();
        $response = Response::create($result, $type)->header($header);
        
        throw new HttpResponseException($response);
    }
    
    /**
     * Ajax方式返回数据到客户端
     * @access protected
     * @param mixed $data 要返回的数据
     * @param String $type AJAX返回数据格式
     * @return void
     */
    protected function ajaxReturn($data, $type = '') {
        if (empty($type))
            $type = Config::get('app.DEFAULT_AJAX_RETURN');
        switch (strtoupper($type)) {
            case 'JSON' :
                // 返回JSON数据格式到客户端 包含状态信息
                header('Content-Type:application/json; charset=utf-8');
                exit(json_encode($data));
            case 'XML' :
                // 返回xml格式数据
                header('Content-Type:text/xml; charset=utf-8');
                exit(xml_encode($data));
            case 'JSONP':
                // 返回JSON数据格式到客户端 包含状态信息
                header('Content-Type:application/json; charset=utf-8');
                $handler = isset($_GET[C('VAR_JSONP_HANDLER')]) ? $_GET[C('VAR_JSONP_HANDLER')] : C('DEFAULT_JSONP_HANDLER');
                exit($handler . '(' . json_encode($data) . ');');
            case 'EVAL' :
                // 返回可执行的js脚本
                header('Content-Type:text/html; charset=utf-8');
                exit($data);
        }
    }
    
    /**
     * URL重定向
     * @access protected
     * @param string $url 跳转的URL表达式
     * @param integer $code http code
     * @param array $with 隐式传参
     * @return void
     */
    protected function redirect($url, $code = 302, $with = []) {
        $response = Response::create($url, 'redirect');
        $response->code($code)->with($with);
        
        throw new HttpResponseException($response);
    }
    
    /**
     * 获取当前的response 输出类型
     * @access protected
     * @return string
     */
    protected function getResponseType() {
        return request::isJson() || request::isAjax() ? 'json' : 'html';
    }
    
    // 成功响应
    protected function successResponse($message) {
        if(is_array($message)){
            return array_merge(['code' => 200], $message);
        }
        else{
            return ['code' => 200, 'message' => $message];
        }
        
    }
    // 错误响应
    protected function errorResponse($message) {
        if(is_array($message)){
            return array_merge(['code' => 400], $message);
        }
        else{
            return ['code' => 400, 'message' => $message];
        }
    }
 
    // 正确响应
    protected function successResponseHtml($title, $message, $url) {
        View::assign('title', $title);
        View::assign('content', $message);
        View::assign('url', $url);
        View::assign('color', 'success');
        View::assign('buttonType', 'primary');
        return View::fetch('common/success');
    }
 
    // 错误响应
    protected function errorResponseHtml($title, $message, $url) {
        View::assign('title', $title);
        View::assign('content', $message);
        View::assign('url', $url);
        View::assign('color', 'error');
        View::assign('buttonType', 'danger');
        return View::fetch('common/success');
    }
 
}