BaseController.php 2.4 KB
<?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;
    }
}