|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace ProgrammatorDev\Api; |
| 4 | + |
| 5 | +use ProgrammatorDev\Api\Builder\ResponseBuilder; |
| 6 | +use Psr\Http\Message\ResponseInterface; |
| 7 | +use RuntimeException; |
| 8 | +use SimpleXMLElement; |
| 9 | + |
| 10 | +final class ResponseDecoder |
| 11 | +{ |
| 12 | + public function __construct( |
| 13 | + private readonly ResponseBuilder $responseBuilder |
| 14 | + ) {} |
| 15 | + |
| 16 | + /** |
| 17 | + * @throws \JsonException |
| 18 | + * @throws RuntimeException |
| 19 | + */ |
| 20 | + public function decode(ResponseInterface $response): mixed |
| 21 | + { |
| 22 | + $response->getBody()->rewind(); |
| 23 | + $contents = $response->getBody()->getContents(); |
| 24 | + |
| 25 | + return match ($this->responseBuilder->format()) { |
| 26 | + ResponseFormat::Raw => $contents, |
| 27 | + ResponseFormat::Json => $this->decodeJson($contents), |
| 28 | + ResponseFormat::Xml => $this->decodeXml($contents), |
| 29 | + ResponseFormat::Custom => $this->decodeCustom($response), |
| 30 | + }; |
| 31 | + } |
| 32 | + |
| 33 | + /** |
| 34 | + * @throws \JsonException |
| 35 | + */ |
| 36 | + private function decodeJson(string $contents): mixed |
| 37 | + { |
| 38 | + return $contents === '' |
| 39 | + ? null |
| 40 | + : json_decode($contents, true, flags: JSON_THROW_ON_ERROR); |
| 41 | + } |
| 42 | + |
| 43 | + private function decodeXml(string $contents): ?SimpleXMLElement |
| 44 | + { |
| 45 | + if ($contents === '') { |
| 46 | + return null; |
| 47 | + } |
| 48 | + |
| 49 | + $previous = libxml_use_internal_errors(true); |
| 50 | + libxml_clear_errors(); |
| 51 | + |
| 52 | + $xml = simplexml_load_string($contents); |
| 53 | + $errors = libxml_get_errors(); |
| 54 | + |
| 55 | + libxml_clear_errors(); |
| 56 | + libxml_use_internal_errors($previous); |
| 57 | + |
| 58 | + if (!$xml instanceof SimpleXMLElement) { |
| 59 | + $message = $errors[0]->message ?? 'Invalid XML response body.'; |
| 60 | + |
| 61 | + throw new RuntimeException(trim($message)); |
| 62 | + } |
| 63 | + |
| 64 | + return $xml; |
| 65 | + } |
| 66 | + |
| 67 | + private function decodeCustom(ResponseInterface $response): mixed |
| 68 | + { |
| 69 | + $decoder = $this->responseBuilder->customDecoder(); |
| 70 | + |
| 71 | + if ($decoder === null) { |
| 72 | + throw new RuntimeException('A custom response decoder must be configured.'); |
| 73 | + } |
| 74 | + |
| 75 | + return $decoder($response); |
| 76 | + } |
| 77 | +} |
0 commit comments