分享自己封装的api返回类

欢迎大佬拍砖 😘 😘

<?php
/**
 * Created by PhpStorm.
 * User: ailuoy
 * Date: 2017/5/13
 * Time: 15:15
 */

namespace App\Traits;

use Response;
use Illuminate\Http\Resources\Json\ResourceCollection;
use Symfony\Component\HttpFoundation\Response as FoundationResponse;

trait ApiResponse
{
    /**
     * 200 OK - [GET]:服务器成功返回用户请求的数据,该操作是幂等的(Idempotent)。
     *
     * @param null $data
     * @param null $message
     * @param      $headers
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function apiGet ($data = null, $message = null, $headers = [])
    {
        return $this->apiSucceed($data, $message, FoundationResponse::HTTP_OK, $headers);
    }

    /**
     * 201 CREATED - [POST/PUT/PATCH]:用户新建或修改数据成功。
     *
     * @param null $data
     * @param null $message
     * @param      $headers
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function apiCreated ($data = null, $message = null, $headers = [])
    {
        $message = $message ? $message : 'Created';

        return $this->apiSucceed($data, $message, FoundationResponse::HTTP_CREATED, $headers);
    }

    /**
     * 202 Accepted - [*]:表示一个请求已经进入后台排队(异步任务)
     *
     * @param null $data
     * @param null $message
     * @param      $headers
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function apiAccepted ($data = null, $message = null, $headers = [])
    {
        $message = $message ? $message : 'Accepted';

        return $this->apiSucceed($data, $message, FoundationResponse::HTTP_ACCEPTED, $headers);
    }

    /**
     * 204 NO CONTENT - [DELETE]:用户删除数据成功。
     *
     * @param null $data
     * @param null $message
     * @param      $headers
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function apiDeleted ($data = null, $message = null, $headers = [])
    {
        $message = $message ? $message : 'Deleted';

        return $this->apiSucceed($data, $message, FoundationResponse::HTTP_NO_CONTENT, $headers);
    }

    /**
     * 400 INVALID REQUEST - [POST/PUT/PATCH]:用户发出的请求有错误,服务器没有进行新建或修改数据的操作,该操作是幂等的。
     *
     * @param null $data
     * @param null $message
     * @param      $headers
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function apiBadRequest ($message = null, $data = null, $headers = [])
    {
        $message = $message ? $message : 'Bad Request';

        return $this->apiFailed($message, $data, FoundationResponse::HTTP_BAD_REQUEST, $headers);
    }

    /**
     * 401 Unauthorized - [*]:表示用户没有权限(令牌、用户名、密码错误)。
     *
     * @param null $data
     * @param null $message
     * @param      $headers
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function apiUnauthorized ($message = null, $data = null, $headers = [])
    {
        $message = $message ? $message : 'Unauthorized';

        return $this->apiFailed($message, $data, FoundationResponse::HTTP_UNAUTHORIZED, $headers);
    }

    /**
     * 402 Parameters Missing - [POST/PUT/PATCH]:用户请求参数不全
     *
     * @param null $data
     * @param null $message
     * @param      $headers
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function apiParametersMissing ($message = null, $data = null, $headers = [])
    {
        $message = $message ? $message : 'Parameters Missing';

        return $this->apiFailed($message, $data, FoundationResponse::HTTP_PAYMENT_REQUIRED, $headers);
    }

    /**
     * 402 Parameters Error - [POST/PUT/PATCH]:用户请求参数错误
     *
     * @param null $data
     * @param null $message
     * @param      $headers
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function apiParametersError ($message = null, $data = null, $headers = [])
    {
        $message = $message ? $message : 'Parameters Error';

        return $this->apiFailed($message, $data, FoundationResponse::HTTP_PAYMENT_REQUIRED, $headers);
    }

    /**
     * 403 Forbidden - [*] 表示用户得到授权(与401错误相对),但是访问是被禁止的。
     *
     * @param null $data
     * @param null $message
     * @param      $headers
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function apiForbidden ($message = null, $data = null, $headers = [])
    {
        $message = $message ? $message : 'Forbidden';

        return $this->apiFailed($message, $data, FoundationResponse::HTTP_FORBIDDEN, $headers);
    }

    /**
     * 404 NOT FOUND - [*]:用户发出的请求针对的是不存在的记录,服务器没有进行操作,该操作是幂等的。
     *
     * @param null $data
     * @param null $message
     * @param      $headers
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function apiNotFound ($message = null, $data = null, $headers = [])
    {
        $message = $message ? $message : 'Not Found';

        return $this->apiFailed($message, $data, FoundationResponse::HTTP_NOT_FOUND, $headers);
    }

    /**
     * 406 Not Acceptable - [GET]:用户请求的格式不可得(比如用户请求JSON格式,但是只有XML格式)。
     *
     * @param null $data
     * @param null $message
     * @param      $headers
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function apiNotAcceptable ($message = null, $data = null, $headers = [])
    {
        $message = $message ? $message : 'Request Format Error';

        return $this->apiFailed($message, $data, FoundationResponse::HTTP_NOT_ACCEPTABLE, $headers);
    }

    /**
     * 410 Gone -[GET]:用户请求的资源被永久删除,且不会再得到的。
     *
     * @param null $data
     * @param null $message
     * @param      $headers
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function apiGone ($message = null, $data = null, $headers = [])
    {
        $message = $message ? $message : 'Resources Deleted';

        return $this->apiFailed($message, $data, FoundationResponse::HTTP_GONE, $headers);
    }

    /**
     * 422 Unprocessable entity - [POST/PUT/PATCH] 当创建一个对象时,发生一个验证错误。
     *
     * @param null $data
     * @param null $message
     * @param      $headers
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function apiUnprocessableEntity ($message = null, $data = null, $headers = [])
    {
        $message = $message ? $message : 'Created Validate Error';

        return $this->apiFailed($message, $data, FoundationResponse::HTTP_UNPROCESSABLE_ENTITY, $headers);
    }

    /**
     * 500 INTERNAL SERVER ERROR - [*]:服务器发生错误,用户将无法判断发出的请求是否成功。
     *
     * @param null $data
     * @param null $message
     * @param      $headers
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function apiInternalServerError ($message = null, $data = null, $headers = [])
    {
        $message = $message ? $message : 'Server Error';

        return $this->apiFailed($message, $data, FoundationResponse::HTTP_INTERNAL_SERVER_ERROR, $headers);
    }

    /**
     * 根据参数返回api的结果[成功]
     *
     * @param       $data
     * @param null  $message
     * @param null  $status_code
     * @param array $header
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function apiSucceed ($data = null, $message = null, $status_code = null, $header = [])
    {
        $response = [
            'code' => $status_code,
            'msg'  => $message,
            'data' => $data
        ];

        if (!$message) unset($response['msg']);
        if (!$data) unset($response['data']);

        return Response::json($response, $status_code, $header);
    }

    /**
     * 根据参数返回api的结果[失败]
     *
     * @param null  $message
     * @param null  $errors
     * @param null  $status_code
     * @param array $header
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function apiFailed ($message = null, $errors = null, $status_code = null, $header = [])
    {
        $response = ['code' => $status_code];

        if ($message) $response['msg'] = $message;
        if ($errors) $response['errors'] = $errors;

        return Response::json($response, $status_code, $header);
    }

    /**
     * 从Api资源中分离出分页数据,并且返回
     * 因为直接返回是没有分页数据的 =.=!!
     *
     * @param ResourceCollection $collection
     *
     * @return array
     */
    public function separatePagination (ResourceCollection $collection)
    {
        $page = $collection->resource->toArray();
        unset($page['data']);
        if (!$page) throw new Exception('数据没有分页数据');
        $next_page_number = false;
        $prev_page_number = false;
        if (isset($page['next_page_url']) && $page['next_page_url']) {
            $_query = convertUrlQuery(parse_url($page['next_page_url'], PHP_URL_QUERY));
            $next_page_number = (int)$_query['page'];
        }
        if (isset($page['prev_page_url']) && $page['prev_page_url']) {
            $_query = convertUrlQuery(parse_url($page['prev_page_url'], PHP_URL_QUERY));
            $prev_page_number = (int)$_query['page'];
        }
        /**
         *
         * next_page_number 下一页页数
         * prev_page_number 上一页页数
         */
        $page['next_page_number'] = $next_page_number;
        $page['prev_page_number'] = $prev_page_number;

        return [
            'data'       => $this->separateData($collection),
            'pagination' => $page
        ];
    }

    /**
     * 分离ResourceCollection之后的数据,
     *
     * @param ResourceCollection $collection
     *
     * @return mixed
     */
    public function separateData (ResourceCollection $collection)
    {
        return $collection->toArray(request());
    }

    /**
     * 从Request验证的errors中剥离出第一个错误
     *
     * @param array $errors
     *
     * @return array
     */
    public function apiFirstErrors (array $errors)
    {
        return [
            array_first(array_keys($errors)) => array_first($errors)[0]
        ];
    }

    /**
     * 获得所有错误
     *
     * @param array $errors
     *
     * @return array
     */
    public function getAllErrors (array $errors)
    {
        $response = [];
        foreach ($errors as $key => $error) {
            $response[ $key ] = $error[0];
        }

        return $response;
    }

}