Json.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php declare(strict_types=1);
  2. /**
  3. * PrivateBin
  4. *
  5. * a zero-knowledge paste bin
  6. *
  7. * @link https://github.com/PrivateBin/PrivateBin
  8. * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
  9. * @license https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  10. */
  11. namespace PrivateBin;
  12. use Exception;
  13. /**
  14. * Json
  15. *
  16. * Provides JSON functions in an object oriented way.
  17. */
  18. class Json
  19. {
  20. /**
  21. * Returns a string containing the JSON representation of the given input
  22. *
  23. * @access public
  24. * @static
  25. * @param mixed $input
  26. * @throws Exception
  27. * @return string
  28. */
  29. public static function encode(&$input)
  30. {
  31. $jsonString = json_encode($input);
  32. self::_detectError();
  33. return $jsonString;
  34. }
  35. /**
  36. * Returns an array with the contents as described in the given JSON input
  37. *
  38. * @access public
  39. * @static
  40. * @param string $input
  41. * @throws Exception
  42. * @return mixed
  43. */
  44. public static function decode(&$input)
  45. {
  46. $output = json_decode($input, true);
  47. self::_detectError();
  48. return $output;
  49. }
  50. /**
  51. * Detects JSON errors and raises an exception if one is found
  52. *
  53. * @access private
  54. * @static
  55. * @throws Exception
  56. * @return void
  57. */
  58. private static function _detectError()
  59. {
  60. $errorCode = json_last_error();
  61. if ($errorCode === JSON_ERROR_NONE) {
  62. return;
  63. }
  64. $message = 'A JSON error occurred';
  65. if (function_exists('json_last_error_msg')) {
  66. $message .= ': ' . json_last_error_msg();
  67. }
  68. $message .= ' (' . $errorCode . ')';
  69. throw new Exception($message, 90);
  70. }
  71. }