|
4 | 4 |
|
5 | 5 | namespace App\Http; |
6 | 6 |
|
| 7 | +use LogicException; |
7 | 8 | use Psr\Http\Message\ResponseInterface; |
8 | 9 | use Yiisoft\DataResponse\DataResponse; |
9 | 10 | use Yiisoft\DataResponse\DataResponseFormatterInterface; |
10 | 11 | use Yiisoft\DataResponse\Formatter\JsonDataResponseFormatter; |
| 12 | +use Yiisoft\Http\Status; |
11 | 13 |
|
12 | | -final class ApiResponseFormatter implements DataResponseFormatterInterface |
| 14 | +use function sprintf; |
| 15 | + |
| 16 | +final readonly class ApiResponseFormatter implements DataResponseFormatterInterface |
13 | 17 | { |
14 | | - public function __construct(private ApiResponseDataFactory $apiResponseDataFactory, private JsonDataResponseFormatter $jsonDataResponseFormatter) {} |
| 18 | + public function __construct( |
| 19 | + private JsonDataResponseFormatter $jsonDataResponseFormatter, |
| 20 | + ) {} |
15 | 21 |
|
16 | 22 | public function format(DataResponse $dataResponse): ResponseInterface |
17 | 23 | { |
18 | | - $response = $dataResponse->withData( |
19 | | - $this->apiResponseDataFactory |
20 | | - ->createFromResponse($dataResponse) |
21 | | - ->toArray(), |
| 24 | + $data = $dataResponse->getStatusCode() === Status::OK |
| 25 | + ? $this->createSuccessData($dataResponse) |
| 26 | + : $this->createFailedData($dataResponse); |
| 27 | + |
| 28 | + return $this->jsonDataResponseFormatter->format( |
| 29 | + $dataResponse->withData($data), |
22 | 30 | ); |
| 31 | + } |
| 32 | + |
| 33 | + private function createSuccessData(DataResponse $response): array |
| 34 | + { |
| 35 | + $data = $response->getData(); |
| 36 | + if ($data !== null && !is_array($data)) { |
| 37 | + throw new LogicException( |
| 38 | + sprintf( |
| 39 | + 'The response data must be either null or an array. Got %s.', |
| 40 | + get_debug_type($data), |
| 41 | + ), |
| 42 | + ); |
| 43 | + } |
| 44 | + |
| 45 | + return [ |
| 46 | + 'status' => 'success', |
| 47 | + 'data' => $data, |
| 48 | + ]; |
| 49 | + } |
23 | 50 |
|
24 | | - return $this->jsonDataResponseFormatter->format($response); |
| 51 | + private function createFailedData(DataResponse $response): array |
| 52 | + { |
| 53 | + $data = $response->getData(); |
| 54 | + return [ |
| 55 | + 'status' => 'failed', |
| 56 | + 'error_message' => is_string($data) && $data !== '' ? $data : 'Unknown error', |
| 57 | + 'error_code' => $response->getStatusCode(), |
| 58 | + ]; |
25 | 59 | } |
26 | 60 | } |
0 commit comments