WebApiResponse.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. namespace App\Helpers;
  3. use Illuminate\Http\JsonResponse;
  4. trait WebApiResponse
  5. {
  6. public function succeed(array|null $data = null, array|null $addition = null, array $codeResponse = ResponseEnum::HTTP_OK): JsonResponse // 成功
  7. {
  8. return $this->jsonResponse('success', $codeResponse, $data, $addition);
  9. }
  10. private function jsonResponse(string $status, array $codeResponse, array|null $data = null, array|null $addition = null): JsonResponse // 返回数据
  11. {
  12. [$code, $message] = $codeResponse;
  13. if ($status === 'success') {
  14. $etag = self::abortIfNotModified($data);
  15. }
  16. $code = $code < 1000 ? $code : (int) ($code / 1000);
  17. $data = compact('status', 'code', 'data', 'message');
  18. if (isset($addition)) {
  19. $data = array_merge($data, $addition);
  20. }
  21. return response()->json($data, $code, ['ETAG' => $etag ?? '']);
  22. }
  23. private static function abortIfNotModified(array|null $data): string // 检查数据是否有变动
  24. {
  25. $req = request();
  26. if (! $req->isMethod('GET')) { // Only for "GET" method
  27. return '';
  28. }
  29. $etag = sha1(json_encode($data));
  30. if (! empty($req->header('IF-NONE-MATCH')) && hash_equals($etag, $req->header('IF-NONE-MATCH'))) {
  31. abort(304);
  32. }
  33. return $etag;
  34. }
  35. public function failed(array $codeResponse = ResponseEnum::HTTP_ERROR, array|null $data = null): JsonResponse // 失败
  36. {
  37. return $this->jsonResponse('fail', $codeResponse, $data);
  38. }
  39. }