Serializable.php 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. declare(strict_types=1);
  3. namespace Yansongda\Supports\Traits;
  4. use RuntimeException;
  5. trait Serializable
  6. {
  7. /**
  8. * toJson.
  9. *
  10. * @author yansongda <me@yansongda.cn>
  11. *
  12. * @return string
  13. */
  14. public function toJson()
  15. {
  16. return $this->serialize();
  17. }
  18. /**
  19. * Specify data which should be serialized to JSON.
  20. *
  21. * @see https://php.net/manual/en/jsonserializable.jsonserialize.php
  22. *
  23. * @return mixed data which can be serialized by <b>json_encode</b>,
  24. * which is a value of any type other than a resource
  25. *
  26. * @since 5.4.0
  27. */
  28. public function jsonSerialize()
  29. {
  30. if (method_exists($this, 'toArray')) {
  31. return $this->toArray();
  32. }
  33. return [];
  34. }
  35. /**
  36. * String representation of object.
  37. *
  38. * @see https://php.net/manual/en/serializable.serialize.php
  39. *
  40. * @return string the string representation of the object or null
  41. *
  42. * @since 5.1.0
  43. */
  44. public function serialize()
  45. {
  46. if (method_exists($this, 'toArray')) {
  47. return json_encode($this->toArray());
  48. }
  49. return json_encode([]);
  50. }
  51. /**
  52. * Constructs the object.
  53. *
  54. * @see https://php.net/manual/en/serializable.unserialize.php
  55. *
  56. * @param string $serialized <p>
  57. * The string representation of the object.
  58. * </p>
  59. *
  60. * @since 5.1.0
  61. */
  62. public function unserialize($serialized)
  63. {
  64. $data = json_decode($serialized, true);
  65. if (JSON_ERROR_NONE !== json_last_error()) {
  66. throw new RuntimeException('Invalid Json Format');
  67. }
  68. foreach ($data as $key => $item) {
  69. if (method_exists($this, 'set')) {
  70. $this->set($key, $item);
  71. }
  72. }
  73. }
  74. }