BaseController.php
2.4 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php
namespace App\Http\Controllers\Bside;
use App\Enums\Common\Code;
use App\Http\Controllers\Controller;
use App\Utils\EncryptUtils;
use \Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
class BaseController extends Controller
{
protected $param = [];//所有请求参数
protected $token = ''; //token
protected $request = [];//助手函数
protected $allCount = 10;//总条数
protected $p = 1;//当前页
protected $row = 20;//每页条数
protected $header = [];//设置请求头参数
/**
* 获取所有参数
*/
public function __construct(Request $request)
{
$this->request = $request;
$this->param = $request->all();
$this->token = $request->header('token');
}
/**
* 成功返回
* @param array $data
* @param string $code
* @param bool $objectData
* @return JsonResponse
* @throws \Psr\Container\ContainerExceptionInterface
* @throws \Psr\Container\NotFoundExceptionInterface
*/
function success(array $data = [], string $code = Code::SUCCESS, bool $objectData = false): JsonResponse
{
if ($objectData) {
$data = (object)$data;
}
$code = Code::fromValue($code);
$response = [
'code' => $code->value,
'data' => $data,
'msg' => $code->description,
];
//加密-返回数据
if (config('app.params_encrypt')) {
$k = config('app.params_encrypt_key');
$i = config('app.params_encrypt_iv');
$response = [
'p' => (new EncryptUtils())->openssl_en($response, $k, $i)];
}
return response()->json($response)->header($this->header);
}
/**
* post方法请求输出数据
* @param type $data
* @return type
*/
protected function result($list) {
$data['data'] = $list;
$data['page'] = $this->setPages();
$this->success($data);
}
/**
* 设置分页返回参数()
*/
protected function setPages() {
$page_count = $this->allCount > $this->row ? ceil($this->allCount / $this->row) : 1;
$this->header['Total-Count'] = $this->allCount; //总条数
$this->header['Page-Count'] = $page_count; //总页数
$this->header['Current-Page'] = $this->p; //当前页数
$this->header['Per-Page'] = $this->row; //每页条数
return $this->header;
}
}