Passed
Push — main ( 905b59...2dc2b0 )
by Gabriel
14:02
created

SerializableTrait::__serialize()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
c 0
b 0
f 0
nc 2
nop 0
dl 0
loc 8
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace ByTIC\DataObjects\Behaviors\Serializable;
6
7
/**
8
 * Trait Serializable
9
 * @package ByTIC\DataObjects\Behaviors\Serializable
10
 *
11
 * @property array $serializable
12
 */
13
trait SerializableTrait
14
{
15
    /**
16
     * @var array List of attribute names which should be stored in serialized form
17
     *
18
     *  protected $serializable = [];
19
     */
20
21
22
    /**
23
     * The custom Carbon JSON serializer.
24
     *
25
     * @var callable|null
26
     */
27
    protected static $serializer;
28
29
    public function __serialize(): array
30
    {
31
        $properties = $this->__sleep();
32
        $data = [];
33
        foreach ($properties as $property) {
34
            $data[$property] = $this->{$property};
35
        }
36
        return $data;
37
    }
38
39
    /**
40
     * @internal
41
     */
42
    public function serialize(): string
43
    {
44
        return serialize($this->__serialize());
45
    }
46
47
    /**
48
     * @param callable $callback
49
     * @return void
50
     */
51
    public static function serializeUsing($callback)
52
    {
53
        static::$serializer = $callback;
54
    }
55
56
    public function __unserialize(array $data): void
57
    {
58
        foreach ($data as $property => $value) {
59
            $this->{$property} = $value;
60
        }
61
    }
62
63
    /**
64
     * @param $data
65
     */
66
    public function unserialize($data)
67
    {
68
        $data = @unserialize($data);
69
        if (!is_array($data)) {
70
            return;
71
        }
72
73
        $this->__unserialize($data);
74
    }
75
76
    /**
77
     * @return array
78
     */
79
    public function __sleep()
80
    {
81
        return $this->serializable;
82
    }
83
84
    public function __wakeup()
85
    {
86
        if (get_parent_class() && method_exists(parent::class, '__wakeup')) {
87
            parent::__wakeup();
88
        }
89
    }
90
}
91