Passed
Push — main ( c84275...1d7014 )
by Gabriel
03:41
created

SerializableTrait   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 60
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 16
c 1
b 0
f 1
dl 0
loc 60
rs 10
wmc 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A __sleep() 0 3 1
A serialize() 0 8 2
A unserialize() 0 8 3
A __wakeup() 0 4 3
A serializeUsing() 0 3 1
1
<?php
2
3
namespace ByTIC\DataObjects\Behaviors\Serializable;
4
5
/**
6
 * Trait Serializable
7
 * @package ByTIC\DataObjects\Behaviors\Serializable
8
 *
9
 * @property array $serializable
10
 */
11
trait SerializableTrait
12
{
13
    /**
14
     * @var array List of attribute names which should be stored in serialized form
15
     *
16
     *  protected $serializable = [];
17
     */
18
19
20
    /**
21
     * The custom Carbon JSON serializer.
22
     *
23
     * @var callable|null
24
     */
25
    protected static $serializer;
26
27
    /**
28
     * @return string
29
     */
30
    public function serialize(): string
31
    {
32
        $properties = $this->__sleep();
33
        $data = [];
34
        foreach ($properties as $property) {
35
            $data[$property] = $this->{$property};
36
        }
37
        return serialize($data);
38
    }
39
40
    public static function serializeUsing($callback)
41
    {
42
        static::$serializer = $callback;
43
    }
44
45
    /**
46
     * @param $data
47
     */
48
    public function unserialize($data)
49
    {
50
        $data = @unserialize($data);
51
        if (!is_array($data)) {
52
            return;
53
        }
54
        foreach ($data as $property => $value) {
55
            $this->{$property} = $value;
56
        }
57
    }
58
59
    /**
60
     * @return array
61
     */
62
    public function __sleep()
63
    {
64
        return $this->serializable;
65
    }
66
67
    public function __wakeup()
68
    {
69
        if (get_parent_class() && method_exists(parent::class, '__wakeup')) {
70
            parent::__wakeup();
71
        }
72
    }
73
}
74