Response.php 2.2 KB
<?php

namespace Helper;

use Illuminate\Http\Exceptions\HttpResponseException;

/**
 * 返回api数据
 * @author:dc
 * @time 2023/2/4 13:54
 * Class Response
 * @package Helper
 */
final class Response {

    /**
     * 消息
     * @var string
     */
    private string $message = '';

    /**
     * 状态码
     * @var int
     */
    private int $status = 200;

    /**
     * 返回的数据
     * @var array
     */
    private mixed $data = [];


    /**
     * 头部
     * @var array
     */
    private array $header = [
        'Content-Type'=>'application/json; charset=UTF-8'
    ];

    /**
     * 消息内容
     * @param string $message
     * @author:dc
     * @time 2023/2/4 14:32
     * @return $this
     */
    public function message(string $message) {
        $this->message  =  $message;
        return $this;
    }


    /**
     * 状态码
     * @param int $status
     * @author:dc
     * @time 2023/2/4 14:35
     * @return $this
     */
    public function status(int $status) {
        $this->status  =  $status;
        return $this;
    }

    /**
     * 头部
     * @param $header
     * @author:dc
     * @time 2023/2/4 14:42
     * @return $this
     */
    public function header($header) {
        $this->header   =   array_merge($this->header, $header);
        return $this;
    }


    /**
     * 数据
     * @param mixed $data
     * @author:dc
     * @time 2023/2/4 14:37
     * @return $this
     */
    public function data(mixed $data) {
        $this->data =   $data;
        return $this;
    }


    /**
     * to json
     * @return \Illuminate\Http\JsonResponse
     * @author:dc
     * @time 2023/2/4 14:54
     */
    public function toJson() {
        return response()->json($this->toArray(),$this->status,$this->header,JSON_UNESCAPED_UNICODE);
    }

    /**
     * to array
     * @return array
     * @author:dc
     * @time 2023/2/4 14:44
     */
    public function toArray() {
        return [
            'status'    =>  $this->status,
            'data'    =>  $this->data,
            'message'   =>  $this->message
        ];
    }


    /**
     * @author:dc
     * @time 2023/2/4 15:04
     */
    public function throw() {
        throw new HttpResponseException($this->toJson());
    }


}