PayloadParserTrait.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace Aws\Api\Parser;
  3. use Aws\Api\Parser\Exception\ParserException;
  4. use Psr\Http\Message\ResponseInterface;
  5. trait PayloadParserTrait
  6. {
  7. /**
  8. * @param string $json
  9. *
  10. * @throws ParserException
  11. *
  12. * @return array
  13. */
  14. private function parseJson($json, $response)
  15. {
  16. $jsonPayload = json_decode($json, true);
  17. if (JSON_ERROR_NONE !== json_last_error()) {
  18. throw new ParserException(
  19. 'Error parsing JSON: ' . json_last_error_msg(),
  20. 0,
  21. null,
  22. ['response' => $response]
  23. );
  24. }
  25. return $jsonPayload;
  26. }
  27. /**
  28. * @param string $xml
  29. *
  30. * @throws ParserException
  31. *
  32. * @return \SimpleXMLElement
  33. */
  34. protected function parseXml($xml, $response)
  35. {
  36. $priorSetting = libxml_use_internal_errors(true);
  37. try {
  38. libxml_clear_errors();
  39. $xmlPayload = new \SimpleXMLElement($xml);
  40. if ($error = libxml_get_last_error()) {
  41. throw new \RuntimeException($error->message);
  42. }
  43. } catch (\Exception $e) {
  44. throw new ParserException(
  45. "Error parsing XML: {$e->getMessage()}",
  46. 0,
  47. $e,
  48. ['response' => $response]
  49. );
  50. } finally {
  51. libxml_use_internal_errors($priorSetting);
  52. }
  53. return $xmlPayload;
  54. }
  55. }