BaseController.php 1.5 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 = [];//助手函数
    /**
     * 获取所有参数
     */
    public function __construct(Request $request)
    {
        $this->request = $request;
        $this->param = $request->post();
        $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);
    }
}