Json.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This file is part of Hyperf.
  5. *
  6. * @link https://www.hyperf.io
  7. * @document https://hyperf.wiki
  8. * @contact group@hyperf.io
  9. * @license https://github.com/hyperf/hyperf/blob/master/LICENSE
  10. */
  11. namespace Hyperf\Codec;
  12. use Hyperf\Codec\Exception\InvalidArgumentException;
  13. use Hyperf\Contract\Arrayable;
  14. use Hyperf\Contract\Jsonable;
  15. use Throwable;
  16. class Json
  17. {
  18. /**
  19. * @throws InvalidArgumentException
  20. */
  21. public static function encode(mixed $data, int $flags = JSON_UNESCAPED_UNICODE, int $depth = 512): string
  22. {
  23. if ($data instanceof Jsonable) {
  24. return (string) $data;
  25. }
  26. if ($data instanceof Arrayable) {
  27. $data = $data->toArray();
  28. }
  29. try {
  30. $json = json_encode($data, $flags | JSON_THROW_ON_ERROR, $depth);
  31. } catch (Throwable $exception) {
  32. throw new InvalidArgumentException($exception->getMessage(), (int) $exception->getCode(), $exception);
  33. }
  34. return $json;
  35. }
  36. /**
  37. * @throws InvalidArgumentException
  38. */
  39. public static function decode(string $json, bool $assoc = true, int $depth = 512, int $flags = 0): mixed
  40. {
  41. try {
  42. $decode = json_decode($json, $assoc, $depth, $flags | JSON_THROW_ON_ERROR);
  43. } catch (Throwable $exception) {
  44. throw new InvalidArgumentException($exception->getMessage(), (int) $exception->getCode(), $exception);
  45. }
  46. return $decode;
  47. }
  48. }