Json.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. namespace Illuminate\Database\Eloquent\Casts;
  3. class Json
  4. {
  5. /**
  6. * The custom JSON encoder.
  7. *
  8. * @var callable|null
  9. */
  10. protected static $encoder;
  11. /**
  12. * The custom JSON decode.
  13. *
  14. * @var callable|null
  15. */
  16. protected static $decoder;
  17. /**
  18. * Encode the given value.
  19. */
  20. public static function encode(mixed $value): mixed
  21. {
  22. return isset(static::$encoder) ? (static::$encoder)($value) : json_encode($value);
  23. }
  24. /**
  25. * Decode the given value.
  26. */
  27. public static function decode(mixed $value, ?bool $associative = true): mixed
  28. {
  29. return isset(static::$decoder)
  30. ? (static::$decoder)($value, $associative)
  31. : json_decode($value, $associative);
  32. }
  33. /**
  34. * Encode all values using the given callable.
  35. */
  36. public static function encodeUsing(?callable $encoder): void
  37. {
  38. static::$encoder = $encoder;
  39. }
  40. /**
  41. * Decode all values using the given callable.
  42. */
  43. public static function decodeUsing(?callable $decoder): void
  44. {
  45. static::$decoder = $decoder;
  46. }
  47. }