Skip to content

Commit 378145c

Browse files
committed
feature: Add serialize with Enum values.
1 parent 606a510 commit 378145c

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

composer.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@
1313
"php": ">=7.4 || ^8.0",
1414
"ext-json": "*",
1515
"illuminate/support": "^8.0 || ^9.0",
16-
"spatie/macroable": "1.0.1"
16+
"spatie/macroable": "1.0.1",
17+
"tenantcloud/php-standard": "^1.4"
1718
},
1819
"require-dev": {
1920
"phpunit/phpunit": "^9.0",

src/TenantCloud/DataTransferObjects/IsDataTransferObject.php

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
use Illuminate\Support\Arr;
77
use Illuminate\Support\Str;
88
use Illuminate\Support\Traits\ForwardsCalls;
9+
use TenantCloud\Standard\Enum\ValueEnum;
910
use Webmozart\Assert\Assert;
1011

1112
/**
@@ -17,6 +18,9 @@ trait IsDataTransferObject
1718

1819
protected array $fields = [];
1920

21+
/** @var array<string, class-string<ValueEnum>> */
22+
protected array $enums = [];
23+
2024
private array $data = [];
2125

2226
/**
@@ -42,6 +46,40 @@ public function __call($method, $arguments)
4246
static::throwBadMethodCallException($method);
4347
}
4448

49+
public function __serialize(): array
50+
{
51+
$data = $this->all();
52+
53+
foreach ($data as $key => $item) {
54+
if ($item instanceof ValueEnum) {
55+
$data[$key] = $item->value();
56+
}
57+
}
58+
59+
return [
60+
'fields' => $this->fields,
61+
'enums' => $this->enums,
62+
'data' => $data,
63+
];
64+
}
65+
66+
public function __unserialize(array $data): void
67+
{
68+
$this->fields = $data['fields'];
69+
$this->enums = $data['enums'];
70+
71+
$dataItems = $data['data'];
72+
73+
foreach ($dataItems as $index => $dataItem) {
74+
if ($enum = Arr::get($this->enums, $index)) {
75+
/* @var ValueEnum|null $enum */
76+
$dataItems[$index] = $enum::fromValue($dataItem);
77+
}
78+
}
79+
80+
$this->data = $dataItems;
81+
}
82+
4583
/**
4684
* @return static
4785
*/

0 commit comments

Comments
 (0)