Response.php
2.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
<?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());
}
}