<?php
/**
 * Created by PhpStorm.
 * User: 思维定制
 * Date: 2018/10/27
 * Time: 12:01
 */

namespace App\Http\Controllers\Api\V1;

use App\Library\ErrorCode;
use Illuminate\Http\Request;
use Illuminate\Validation\Validator;

class BaseController extends Controller
{
    public function validateError(Validator $validator, $code = ErrorCode::CLIENT_WRONG_PARAMS)
    {
        return $this->generateApiResponse(null, $code, $validator->errors()->first());
    }

    public function success($data = null, $code = 0, $message = '')
    {
        return $this->generateApiResponse($data, $code, $message);
    }

    public function generateApiResponse($data, $code = 0, $message = '')
    {
        if($code !== 0 && empty($message)) {
            $message = ErrorCode::message($code);
        }
        $ret = [
            'state'     => $code == 0,
            'code'      => $code,
            'message'   => $message,
            'data'      => $data
        ];
        $status = $code === 0 ? 200 : 400;
        return response()->json($ret, $status);
    }
}