2022-07-18 17:37:55 +08:00

91 lines
2.6 KiB
PHP

<?php
namespace App\Http\Controllers\Helpers;
use Illuminate\Http\Response;
use Illuminate\Support\Arr;
use App\ResultStruct\Result;
use Illuminate\Http\JsonResponse;
trait ResponseTrait {
private $_data = [
'code' => ERROR_CODE_OK,
'data' => [],
'message' => ''
];
protected $_headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'POST,GET,OPTIONS,DELETE,PUT',
'Access-Control-Allow-Headers' => 'Origin, X-Requested-With, Content-Type, Accept, Authorization',
'Content-Type' => 'application/json; charset=UTF-8'
];
protected $_errorMessage = [
ERROR_CODE_INTERNAL_ERROR => 'Unable to request server',
];
public function response($code, $data = [], $message = "") {
$this->setCode($code)->setData($data)->setMsg($message);
return new JsonResponse($this->_data, 200, $this->_headers,
JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
public function authExpire($msg = "登陆过期") {
$this->setMsg($msg)->setCode(ERROR_CODE_PERMISSION_NO);
return new JsonResponse($this->_data, 401, $this->_headers,
JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
}
public function foxResponse(Result $res) {
return $this->response($res->getCode(), $res->getData(), $res->getMsg());
}
public function success($data = [], $msg = 'Ok') {
return $this->response(ERROR_CODE_OK, $data, $msg);
}
public function error($code = ERROR_CODE_PARAM_INVALID, $msg = "", $data = []) {
if (empty($msg)) {
$msg = Arr::get($this->_errorMessage, $code, "");
}
return $this->response($code, $data, $msg);
}
protected function setCode($code) {
Arr::set($this->_data, 'code', $code);
return $this;
}
protected function setData($data) {
Arr::set($this->_data, 'data', $data);
return $this;
}
protected function setMsg($msg) {
Arr::set($this->_data, 'message', $msg);
return $this;
}
protected function appendData($data = []) {
$this->_data = array_merge($this->_data, (array)$data);
return $this;
}
protected function setNewData($field, $value) {
Arr::set($this->_data, $field, $value);
return $this;
}
protected function setHeader($name, $value) {
Arr::set($this->_headers, $name, $value);
return $this;
}
protected function download($file, $target_name) {
return \response()->download($file, $target_name, ['Access-Control-Allow-Origin' => '*']);
}
}