?php
namespace App\Services;
use Validator;
class Http
{
/***
* 响应成功返回的函数
*
* @param $message
* @param $content
* @param int $status
* @return \Illuminate\Http\JsonResponse
* @internal param $data
*/
public function success($message,$content="",$status=200)
{
if(is_array($content)count($content)1){
$data['content']=$content;
$data['code']=0;
$data['msg']="数据不存在";
return response()->json($data,$status);
}
$data['content']=$content;
$data['code']=1;
$data['msg']=$message;
return response()->json($data,$status);
}
/***
* 响应错误返回的函数
*
* @param $message
* @param int $status
* @return \Illuminate\Http\JsonResponse
*/
public function error($message,$status=200)
{
$data['code']=0;
$data['msg']=$message;
return response()->json($data,$status);
}
/***
* 响应错误返回的函数
*
* @param $message
* @param $content
* @param int $status
* @return \Illuminate\Http\JsonResponse
*/
public function errorWithData($message,$content,$status=200)
{
$data['code']=0;
$data['data']=$content;
$data['msg']=$message;
return response()->json($data,$status);
}
/***
* 验证字段属性
*
* @param $all
* @param $rules
* @param bool $message
* @return array|bool|string
*/
public function validate($all,$rules,$message=false){
if(!$message){
$message=$this->getMessage();
}
$validator = Validator::make($all, $rules,$message);
if ($validator->fails()) {
$array = array_flatten($validator->errors()->toArray());
$message=implode(' ',$array);
return $message;
}
return false;
}
/***
* 返回验证message
* @return array
*/
public function getMessage(){
return [
'required' => '字段 :attribute 是必须的.',
'unique' => '该数据已经存在.',
'between' => '字段 :attribute 必须在 :min - :max.之间',
];
}
}