-
Notifications
You must be signed in to change notification settings - Fork 2
/
SerializationTrait.php
73 lines (65 loc) · 2.43 KB
/
SerializationTrait.php
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
<?php
namespace Aternos\Taskmaster\Communication\Serialization;
use ReflectionClass;
/**
* Trait SerializationTrait
*
* This trait is used to serialize objects using the #[Serializable] and #[NotSerializable] attributes.
*
* You can use the #[Serializable] attribute to mark properties that should be serialized.
* When using only the #[Serializable] attribute, all properties that are not marked with the
* #[Serializable] attribute will be ignored.
*
* You can use the #[NotSerializable] attribute to mark properties that should not be serialized.
* When using only the #[NotSerializable] attribute, all properties that are not marked with the
* #[NotSerializable] attribute will be serialized.
*
* When using both attributes, all properties MUST be marked with either the #[Serializable] or #[NotSerializable]
* attribute, otherwise an exception will be thrown.
*
* @package Aternos\Taskmaster\Communication\Serialization
*/
trait SerializationTrait
{
public function __serialize(): array
{
$unknown = [];
$serializable = [];
$hasNotSerializable = false;
$hasSerializable = false;
$hasUnknown = false;
foreach ((new ReflectionClass($this))->getProperties() as $property) {
if ($property->isStatic()) {
continue;
}
if ($property->getAttributes(NotSerializable::class)) {
$hasNotSerializable = true;
continue;
}
if ($property->getAttributes(Serializable::class)) {
$hasSerializable = true;
if ($property->isInitialized($this)) {
$serializable[$property->getName()] = $property->getValue($this);
}
continue;
}
$hasUnknown = true;
if ($property->isInitialized($this)) {
$unknown[$property->getName()] = $property->getValue($this);
}
}
if ($hasNotSerializable) {
if (!$hasSerializable) {
return $unknown;
}
if ($hasUnknown) {
throw new \LogicException("Found unknown properties (" . implode(", ", array_keys($unknown)) . ") on object using both, #[Serializable] and #[NotSerializable] attributes.");
}
return $serializable;
}
if ($hasSerializable) {
return $serializable;
}
return $unknown;
}
}