Skip to content

Commit 8574637

Browse files
author
liutao
committed
support enum fill
1 parent 24c4556 commit 8574637

2 files changed

Lines changed: 14 additions & 1 deletion

File tree

src/Data.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,9 @@ public function fill(array $data): static
7474
} elseif ($type->isBuiltin() && !is_null($value)) {
7575
$property->setValue($this, $value);
7676
} elseif (PHP_VERSION_ID > 80100 && enum_exists($type->getName())) {
77+
if (is_int($value) || is_string($value)) {
78+
$value = $type->getName()::from($value);
79+
}
7780
$property->setValue($this, $value);
7881
} elseif (class_exists($type->getName())) {
7982
if (is_array($value)) {

tests/Feature/DataTest.php

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,15 @@
4747
->and(Str::startsWith('hello', 'he'))->toBeTrue();
4848
});
4949

50+
test('enum', function () {
51+
$c = C::from(['name' => '123', 'a' => 'a']);
52+
expect($c->a)->toBe(enumA::A);
53+
54+
});
55+
56+
it('throws exception', function () {
57+
C::from(['name' => '123', 'a' => 'b']);
58+
})->throws(ValueError::class);
5059

5160
#[DataAttribute(toSnakeArray: true)]
5261
class A extends Data
@@ -77,6 +86,7 @@ enum enumA: string
7786
case A = 'a';
7887
}
7988

80-
class D extends Data {
89+
class D extends Data
90+
{
8191
public string|int $name;
8292
}

0 commit comments

Comments
 (0)