Serializable.php
1.2 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
<?php
declare(strict_types=1);
namespace Yansongda\Supports\Traits;
trait Serializable
{
public function __serialize(): array
{
if (method_exists($this, 'toArray')) {
return $this->toArray();
}
return [];
}
public function __unserialize(array $data): void
{
$this->unserializeArray($data);
}
public function __toString(): string
{
return $this->toJson();
}
public function serialize(): ?string
{
return serialize($this);
}
public function unserialize($data): void
{
unserialize($data);
}
/**
* toJson.
*/
public function toJson(int $option = JSON_UNESCAPED_UNICODE): string
{
return json_encode($this->__serialize(), $option);
}
/**
* @return mixed
*/
#[\ReturnTypeWillChange]
public function jsonSerialize()
{
return $this->__serialize();
}
public function unserializeArray(array $data): self
{
foreach ($data as $key => $item) {
if (method_exists($this, 'set')) {
$this->set($key, $item);
}
}
return $this;
}
}