Json.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  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. * @version 1.6.2
  11. */
  12. namespace PrivateBin;
  13. use Exception;
  14. /**
  15. * Json
  16. *
  17. * Provides JSON functions in an object oriented way.
  18. */
  19. class Json
  20. {
  21. /**
  22. * Returns a string containing the JSON representation of the given input
  23. *
  24. * @access public
  25. * @static
  26. * @param mixed $input
  27. * @throws Exception
  28. * @return string
  29. */
  30. public static function encode($input)
  31. {
  32. $jsonString = json_encode($input);
  33. self::_detectError();
  34. return $jsonString;
  35. }
  36. /**
  37. * Returns an array with the contents as described in the given JSON input
  38. *
  39. * @access public
  40. * @static
  41. * @param string $input
  42. * @throws Exception
  43. * @return mixed
  44. */
  45. public static function decode($input)
  46. {
  47. $output = json_decode($input, true);
  48. self::_detectError();
  49. return $output;
  50. }
  51. /**
  52. * Detects JSON errors and raises an exception if one is found
  53. *
  54. * @access private
  55. * @static
  56. * @throws Exception
  57. * @return void
  58. */
  59. private static function _detectError()
  60. {
  61. $errorCode = json_last_error();
  62. if ($errorCode === JSON_ERROR_NONE) {
  63. return;
  64. }
  65. $message = 'A JSON error occurred';
  66. if (function_exists('json_last_error_msg')) {
  67. $message .= ': ' . json_last_error_msg();
  68. }
  69. $message .= ' (' . $errorCode . ')';
  70. throw new Exception($message, 90);
  71. }
  72. }