JsonSerializer.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\TestFramework\Helper;
  7. /**
  8. * Encodes and decodes JSON and checks for errors on these operations
  9. */
  10. class JsonSerializer
  11. {
  12. /**
  13. * @var array JSON Error code to error message mapping
  14. */
  15. private $jsonErrorMessages = [
  16. JSON_ERROR_DEPTH => 'Maximum depth exceeded',
  17. JSON_ERROR_STATE_MISMATCH => 'State mismatch',
  18. JSON_ERROR_CTRL_CHAR => 'Unexpected control character found',
  19. JSON_ERROR_SYNTAX => 'Syntax error, invalid JSON',
  20. ];
  21. /**
  22. * Encode a string as a JSON object with error checking
  23. *
  24. * @param mixed $data
  25. * @return string
  26. * @throws \Exception
  27. */
  28. public function jsonEncode($data)
  29. {
  30. $ret = json_encode($data);
  31. $this->checkJsonError($data);
  32. // return the json String
  33. return $ret;
  34. }
  35. /**
  36. * Decode a JSON string with error checking
  37. *
  38. * @param string $data
  39. * @param bool $asArray
  40. * @throws \Exception
  41. * @return mixed
  42. */
  43. public function jsonDecode($data, $asArray = true)
  44. {
  45. $ret = json_decode($data, $asArray);
  46. $this->checkJsonError($data);
  47. // return the array
  48. return $ret;
  49. }
  50. /**
  51. * Checks for JSON error in the latest encoding / decoding and throws an exception in case of error
  52. *
  53. * @throws \Exception
  54. */
  55. private function checkJsonError()
  56. {
  57. $jsonError = json_last_error();
  58. if ($jsonError !== JSON_ERROR_NONE) {
  59. // find appropriate error message
  60. $message = 'Unknown JSON Error';
  61. if (isset($this->jsonErrorMessages[$jsonError])) {
  62. $message = $this->jsonErrorMessages[$jsonError];
  63. }
  64. throw new \Exception(
  65. 'JSON Encoding / Decoding error: ' . $message . var_export(func_get_arg(0), true),
  66. $jsonError
  67. );
  68. }
  69. }
  70. }