Skip to content

Commit 775b74a

Browse files
author
liutao
committed
support enum toArray
1 parent 8aba17c commit 775b74a

File tree

2 files changed

+24
-4
lines changed

2 files changed

+24
-4
lines changed

src/Data.php

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ public function fill(array $data): static
7676
$property->setValue($this, $value);
7777
} elseif (PHP_VERSION_ID > 80100 && enum_exists($type->getName())) {
7878
if (is_int($value) || is_string($value)) {
79-
$value = $type->getName()::from($value);
79+
$value = $type->getName()::{'from'}($value);
8080
}
8181
$property->setValue($this, $value);
8282
} elseif (class_exists($type->getName())) {
@@ -135,6 +135,9 @@ protected function forValue(mixed $value, bool $toSnake)
135135
return array_map(fn($item) => $this->forValue($item, $toSnake), $value);
136136
}
137137
if (is_object($value)) {
138+
if (PHP_VERSION_ID > 80100 && enum_exists(get_class($value))) {
139+
return $value->value;
140+
}
138141
if ($this->isArrayAble($value)) {
139142
return $value->toArray();
140143
}
@@ -175,7 +178,22 @@ protected function isArrayAble($data): bool
175178
return $data instanceof ArrayAble || is_object($data) && method_exists($data, 'toArray');
176179
}
177180

178-
protected function beforeFill(array $data): void {}
181+
protected function beforeFill(array $data): void
182+
{
183+
}
184+
185+
protected function afterFill(array $data)
186+
{
187+
}
179188

180-
protected function afterFill(array $data) {}
189+
public function __serialize(): array
190+
{
191+
$data = [];
192+
foreach ($this->getStaticReflection()->getProperties() as $property) {
193+
if (!$this->isInsideProperty($property)) {
194+
$data[$property->getName()] = $property->getValue($this);
195+
}
196+
}
197+
return $data;
198+
}
181199
}

tests/Feature/DataTest.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
->and($b->addressDetail)->toBe($a->addressDetail);
2626

2727
$c = C::from(['name' => '123', 'a' => enumA::A]);
28+
$c->toArray();
2829
$c1 = unserialize(serialize($c));
2930
expect($c1)->toBeInstanceOf(C::class);
3031
});
@@ -47,7 +48,8 @@
4748

4849
test('enum', function () {
4950
$c = C::from(['name' => '123', 'a' => 'a']);
50-
expect($c->a)->toBe(enumA::A);
51+
expect($c->a)->toBe(enumA::A)
52+
->and($c->toArray())->toBe(['name' => '123', 'a' => 'a']);
5153
$c = serialize($c);
5254
$c = unserialize($c);
5355
expect($c->a)->toBe(enumA::A);

0 commit comments

Comments
 (0)