ClientApiResponse.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. namespace App\Helpers;
  3. use Illuminate\Http\JsonResponse;
  4. use Illuminate\Http\Request;
  5. trait ClientApiResponse
  6. {
  7. private static string $client;
  8. public function __construct(Request $request)
  9. {
  10. if (str_contains($request->userAgent(), 'bob_vpn')) {
  11. self::$client = 'bob';
  12. }
  13. }
  14. public function setClient(string $client): void
  15. {
  16. self::$client = $client;
  17. }
  18. public function succeed(?array $data = null, ?array $addition = null, array $codeResponse = ResponseEnum::HTTP_OK): JsonResponse
  19. {
  20. return $this->jsonResponse(1, $codeResponse, $data, $addition);
  21. }
  22. private function jsonResponse(int $status, array $codeResponse, array|string|null $data = null, array|null $addition = null): JsonResponse
  23. {
  24. [$code, $message] = $codeResponse;
  25. $code = $code > 1000 ? (int) ($code / 1000) : $code;
  26. if (self::$client === 'bob') { // bob 客户端 返回格式
  27. $result = ['ret' => $status, 'msg' => $message, 'data' => $data];
  28. if (isset($addition)) {
  29. $result = array_merge($result, $addition);
  30. }
  31. } else { // ProxyPanel client api 规范格式
  32. if (isset($data, $addition) && is_array($data)) {
  33. $data = array_merge($data, $addition);
  34. }
  35. $result = ['status' => $status ? 'success' : 'fail', 'code' => $code, 'message' => $message, 'data' => $data ?? $addition];
  36. }
  37. return response()->json($result, $code, ['content-type' => 'application/json']);
  38. }
  39. public function failed(array $codeResponse = ResponseEnum::HTTP_ERROR, array|string|null $data = null): JsonResponse
  40. {
  41. return $this->jsonResponse(0, $codeResponse, is_array($data) ? $data[0] : $data);
  42. }
  43. }