| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- <?php
- declare(strict_types=1);
- namespace SixShop\Wangdian\Response;
- use SixShop\Wangdian\Exception\ApiException;
- /**
- * Handles API response parsing and validation
- */
- class ResponseHandler
- {
- /**
- * Process API response and validate success
- */
- public function handle(array $response): ApiResponse
- {
- return new ApiResponse($response);
- }
- /**
- * Validate if the response indicates success
- */
- public function isSuccess(array $response): bool
- {
- // Wangdian API typically returns 'code' => 0 for success
- return isset($response['code']) && (int) $response['code'] === 0;
- }
- /**
- * Extract error information from response
- */
- public function extractError(array $response): ?array
- {
- if ($this->isSuccess($response)) {
- return null;
- }
- return [
- 'code' => $response['code'] ?? 'unknown',
- 'message' => $response['message'] ?? $response['msg'] ?? 'Unknown error',
- 'data' => $response['data'] ?? null,
- ];
- }
- /**
- * Throw exception if response indicates error
- */
- public function validateOrThrow(array $response): void
- {
- if (!$this->isSuccess($response)) {
- $error = $this->extractError($response);
-
- throw new ApiException(
- message: $error['message'],
- code: 0,
- previous: null,
- context: null,
- apiCode: (string) $error['code'],
- responseData: $response
- );
- }
- }
- }
|