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