ResponseHandler.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. <?php
  2. declare(strict_types=1);
  3. namespace SixShop\Wangdian\Response;
  4. use SixShop\Wangdian\Exception\ApiException;
  5. /**
  6. * Handles API response parsing and validation
  7. */
  8. class ResponseHandler
  9. {
  10. /**
  11. * Process API response and validate success
  12. */
  13. public function handle(array $response): ApiResponse
  14. {
  15. return new ApiResponse($response);
  16. }
  17. /**
  18. * Validate if the response indicates success
  19. */
  20. public function isSuccess(array $response): bool
  21. {
  22. // Wangdian API typically returns 'code' => 0 for success
  23. return isset($response['code']) && (int) $response['code'] === 0;
  24. }
  25. /**
  26. * Extract error information from response
  27. */
  28. public function extractError(array $response): ?array
  29. {
  30. if ($this->isSuccess($response)) {
  31. return null;
  32. }
  33. return [
  34. 'code' => $response['code'] ?? 'unknown',
  35. 'message' => $response['message'] ?? $response['msg'] ?? 'Unknown error',
  36. 'data' => $response['data'] ?? null,
  37. ];
  38. }
  39. /**
  40. * Throw exception if response indicates error
  41. */
  42. public function validateOrThrow(array $response): void
  43. {
  44. if (!$this->isSuccess($response)) {
  45. $error = $this->extractError($response);
  46. throw new ApiException(
  47. message: $error['message'],
  48. code: 0,
  49. previous: null,
  50. context: null,
  51. apiCode: (string) $error['code'],
  52. responseData: $response
  53. );
  54. }
  55. }
  56. }