自己寫了一個簡單的後置中介軟體統一格式

foresttree發表於2019-05-24

使用後置中介軟體來返回介面

自己寫了個統一介面返回

<?php

namespace App\Http\Middleware;

use Closure;

/**
 * 設定一個後置中介軟體統一返回格式,去除null值
 *
 * Class Response
 */
class Response
{
    private $codeDefault = self::SUCCESS;
    private $messageDefault = self::SUCCESS_MSG;

    const SUCCESS = 200;
    const WARNING = 300;
    const ERROR = 400;
    const SUCCESS_MSG = '返回成功';

    public function handle($request, Closure $next)
    {
        $response = $next($request);
        $response = $this->formatData($response->original);

        return response()->json($response);
    }

    /**
     * 格式化資料
     *
     * @param $response
     * @return array
     */
    private function formatData($response)
    {
        if (isset($response['data'])) {
            $response['data'] = $this->isArray($response['data']);
            $response['data'] = $this->nullTransform($response['data']);
        }

        $message = isset($response['message']) ? $response['message'] : '';
        $code = isset($response['code']) ? $response['code'] : $this->codeDefault;
        $data = isset($response['data']) ? $response['data'] : $this->messageDefault;

        return ['code' => $code, 'message' => $message, 'data' => $data];
    }

    /**
     * 去除null值
     *
     * @param $response
     * @return mixed
     */
    private function nullTransform($response)
    {
        $response = $this->isArray($response);
        array_walk_recursive($response, function (&$val) {
            if ($val === null) {
                $val = '';
            }
        });
        return $response;
    }

    /**
     * 判斷變數是否陣列
     *
     * @param $response
     * @return mixed
     */
    private function isArray($response)
    {
        if(!is_array($response)){
            return $response->toArray();
        }
        return $response;
    }
}

控制器只需要直接返回陣列,路由引入該中介軟體。

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章