123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148 |
- <?php
- namespace App\Http\Helpers;
- use Symfony\Component\HttpFoundation\Response as FoundationResponse;
- trait ApiResponse
- {
- /**
- * @var int
- */
- protected $statusCode = FoundationResponse::HTTP_OK;
- protected $token = '';
- /**
- * @return mixed
- */
- public function getStatusCode()
- {
- return $this->statusCode;
- }
- /**
- * @param $statusCode
- * @return $this
- */
- public function setStatusCode($statusCode)
- {
- $this->statusCode = $statusCode;
- return $this;
- }
- /**
- * @param $token
- * @return $this
- */
- public function setToken($token)
- {
- $this->token = $token;
- return $this;
- }
- /**
- * @param $data
- * @return \Illuminate\Http\JsonResponse
- */
- public function respond($data)
- {
- $response = response()->json($data, $this->getStatusCode());
- if ($this->token) {
- $response->headers->set('Authorization', 'Bearer ' . $this->token);
- }
- return $response;
- }
- /**
- * @param $status
- * @param array $data
- * @param null $code
- * @return mixed
- */
- public function status($status, array $data, $code = null)
- {
- if ($code) {
- $this->setStatusCode($code);
- }
- $status = [
- 'status' => $status,
- 'code' => $this->statusCode
- ];
- $data = array_merge($status, $data);
- return $this->respond($data);
- }
- /**
- * @param $message
- * @param int $code
- * @param string $status
- * @return mixed
- */
- /*
- * 格式
- * data:
- * code:422
- * message:xxx
- * status:'error'
- */
- public function failed($message, $code = FoundationResponse::HTTP_BAD_REQUEST, $status = 'error')
- {
- return $this->setStatusCode($code)->message($message, $status);
- }
- /**
- * @param $message
- * @param string $status
- * @return mixed
- */
- public function message($message, $status = "success")
- {
- if(!is_array($message)) {
- $message = [$message];
- }
- return $this->status($status, [
- 'message' => $message
- ]);
- }
- /**
- * @param string $message
- * @return mixed
- */
- public function internalError($message = "Internal Error!")
- {
- return $this->failed($message, FoundationResponse::HTTP_INTERNAL_SERVER_ERROR);
- }
- /**
- * @param string $message
- * @return mixed
- */
- public function created($message = "created")
- {
- return $this->setStatusCode(FoundationResponse::HTTP_CREATED)
- ->message($message);
- }
- /**
- * @param $data
- * @param string $status
- * @return mixed
- */
- public function success($data, $status = "success")
- {
- return $this->status($status, compact('data'));
- }
- /**
- * @param string $message
- * @return mixed
- */
- public function notFond($message = 'Not Fond!')
- {
- return $this->failed($message, Foundationresponse::HTTP_NOT_FOUND);
- }
- }
|