Skip to content

Commit 0c438cc

Browse files
authored
Update WebmanResponseTrait.php
1 parent c61d23f commit 0c438cc

File tree

1 file changed

+113
-18
lines changed

1 file changed

+113
-18
lines changed

src/Traits/WebmanResponseTrait.php

Lines changed: 113 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,13 @@
99
*/
1010
trait WebmanResponseTrait
1111
{
12+
public static $responseCodeKey = 1; // 1:code msg、2:code message、3:err_code err_msg、errcode errmsg
13+
14+
public static function setResponseCodeKey(int $responseCodeKey = 1)
15+
{
16+
ResponseTrait::$responseCodeKey = $responseCodeKey;
17+
}
18+
1219
public static function string2utf8($string = '')
1320
{
1421
if (empty($string)) {
@@ -42,13 +49,31 @@ public function customPaginate($items, $total, $pageSize = 15)
4249
return $this->paginate($paginate);
4350
}
4451

45-
public function paginate(\Illuminate\Pagination\LengthAwarePaginator $paginate, ?callable $callable = null)
52+
public function paginate($data, ?callable $callable = null)
4653
{
54+
// 处理集合数据
55+
if ($data instanceof \Illuminate\Database\Eloquent\Collection) {
56+
return $this->success(array_map(function ($item) use ($callable) {
57+
if ($callable) {
58+
return $callable($item) ?? $item;
59+
}
60+
61+
return $item;
62+
}, $data->all()));
63+
}
64+
65+
// 处理非分页数据
66+
if (! $data instanceof \Illuminate\Pagination\LengthAwarePaginator) {
67+
return $this->success($data);
68+
}
69+
70+
// 处理分页数据
71+
$paginate = $data;
4772
return $this->success([
4873
'meta' => [
4974
'total' => $paginate->total(),
5075
'current_page' => $paginate->currentPage(),
51-
'per_page' => $paginate->perPage(),
76+
'page_size' => $paginate->perPage(),
5277
'last_page' => $paginate->lastPage(),
5378
],
5479
'data' => array_map(function ($item) use ($callable) {
@@ -57,7 +82,7 @@ public function paginate(\Illuminate\Pagination\LengthAwarePaginator $paginate,
5782
}
5883

5984
return $item;
60-
}, $paginate->items()),
85+
}, $paginate?->items()),
6186
]);
6287
}
6388

@@ -77,12 +102,41 @@ public function success($data = [], $err_msg = 'success', $err_code = 200, $head
77102

78103
$err_msg = static::string2utf8($err_msg);
79104

80-
if ($err_code === 200 && ($config_err_code = config('webman-init-template.response.err_code', 200)) !== $err_code) {
105+
if ($err_code === 200 && ($config_err_code = config('laravel-init-template.response.err_code', 200)) !== $err_code) {
81106
$err_code = $config_err_code;
82107
}
83108

84109
$data = $data ?: null;
85-
$res = compact('err_code', 'err_msg', 'data') + array_filter(compact('meta'));
110+
111+
$res = match (ResponseTrait::$responseCodeKey) {
112+
default => [
113+
'err_code' => $err_code,
114+
'err_msg' => $err_msg,
115+
'data' => $data,
116+
],
117+
1 => [
118+
'err_code' => $err_code,
119+
'err_msg' => $err_msg,
120+
'data' => $data,
121+
],
122+
2 => [
123+
'code' => $err_code,
124+
'message' => $err_msg,
125+
'data' => $data,
126+
],
127+
3 => [
128+
'code' => $err_code,
129+
'msg' => $err_msg,
130+
'data' => $data,
131+
],
132+
4 => [
133+
'errcode' => $err_code,
134+
'errmsg' => $err_msg,
135+
'data' => $data,
136+
],
137+
};
138+
139+
$res = $res + array_filter(compact('meta'));
86140

87141
return \response(
88142
\json_encode($res, \JSON_UNESCAPED_SLASHES|\JSON_UNESCAPED_UNICODE|\JSON_PRETTY_PRINT),
@@ -95,8 +149,36 @@ public function success($data = [], $err_msg = 'success', $err_code = 200, $head
95149

96150
public function fail($err_msg = 'unknown error', $err_code = 400, $data = [], $headers = [])
97151
{
98-
if (! \request()->expectsJson()) {
99-
$err_msg = \json_encode(compact('err_code', 'err_msg', 'data'), \JSON_UNESCAPED_SLASHES|\JSON_UNESCAPED_UNICODE|\JSON_PRETTY_PRINT);
152+
$res = match (ResponseTrait::$responseCodeKey) {
153+
default => [
154+
'err_code' => $err_code,
155+
'err_msg' => $err_msg,
156+
'data' => $data,
157+
],
158+
1 => [
159+
'err_code' => $err_code,
160+
'err_msg' => $err_msg,
161+
'data' => $data,
162+
],
163+
2 => [
164+
'code' => $err_code,
165+
'message' => $err_msg,
166+
'data' => $data,
167+
],
168+
3 => [
169+
'code' => $err_code,
170+
'msg' => $err_msg,
171+
'data' => $data,
172+
],
173+
4 => [
174+
'errcode' => $err_code,
175+
'errmsg' => $err_msg,
176+
'data' => $data,
177+
],
178+
};
179+
180+
if (! \request()->exceptsJson()) {
181+
$err_msg = \json_encode($res, \JSON_UNESCAPED_SLASHES|\JSON_UNESCAPED_UNICODE|\JSON_PRETTY_PRINT);
100182
if (!array_key_exists($err_code, Response::$statusTexts)) {
101183
$err_code = 500;
102184
}
@@ -118,20 +200,33 @@ public function reportableHandle(\Throwable $e)
118200
//
119201
}
120202

121-
public function renderableHandle(\Webman\Http\Request $request, \Throwable $e)
203+
public function renderableHandle()
122204
{
123-
if ($e instanceof \Illuminate\Validation\ValidationException) {
124-
return $this->fail($e->validator->errors()->first(), Response::HTTP_UNPROCESSABLE_ENTITY);
125-
}
205+
return function (\Throwable $e) {
206+
if ($e instanceof \Illuminate\Auth\AuthenticationException) {
207+
return $this->fail('登录失败,请稍后重试', $e->getCode() ?: config('laravel-init-template.auth.unauthorize_code', 401));
208+
}
126209

127-
if ($e instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
128-
return $this->fail('404 Data Not Found.', Response::HTTP_NOT_FOUND);
129-
}
210+
if ($e instanceof \Illuminate\Validation\ValidationException) {
211+
return $this->fail($e->validator->errors()->first(), Response::HTTP_UNPROCESSABLE_ENTITY);
212+
}
130213

131-
if ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
132-
return $this->fail('404 Url Not Found.', Response::HTTP_NOT_FOUND);
133-
}
214+
if ($e instanceof \Illuminate\Database\Eloquent\ModelNotFoundException) {
215+
return $this->fail('404 Data Not Found.', Response::HTTP_NOT_FOUND);
216+
}
217+
218+
if ($e instanceof \Symfony\Component\HttpKernel\Exception\NotFoundHttpException) {
219+
return $this->fail('404 Url Not Found.', Response::HTTP_NOT_FOUND);
220+
}
221+
222+
// \info('error', [
223+
// 'class' => get_class($e),
224+
// 'code' => $e->getCode(),
225+
// 'message' => $e->getMessage(),
226+
// 'file_line' => sprintf('%s:%s', $e->getFile(), $e->getLine()),
227+
// ]);
134228

135-
return $this->fail($e->getMessage(), $e->getCode() ?: Response::HTTP_INTERNAL_SERVER_ERROR);
229+
return $this->fail($e->getMessage(), $e->getCode() ?: Response::HTTP_INTERNAL_SERVER_ERROR);
230+
};
136231
}
137232
}

0 commit comments

Comments
 (0)