Skip to content

Commit 24c4556

Browse files
author
liutao
committed
support union type
1 parent bc162cc commit 24c4556

File tree

2 files changed

+18
-1
lines changed

2 files changed

+18
-1
lines changed

src/Data.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@
1212
use Ltaooo\Data\Traits\ArrayAccessTrait;
1313
use Ltaooo\Data\Util\Str;
1414
use ReflectionClass;
15+
use ReflectionIntersectionType;
1516
use ReflectionProperty;
17+
use ReflectionUnionType;
1618

1719
class Data implements ArrayAble, ArrayAccess, JsonSerializable
1820
{
@@ -67,7 +69,9 @@ public function fill(array $data): static
6769
}
6870
$type = $property->getType();
6971
$value = $data[$camelCasePropertyName] ?? ($data[$snakePropertyName] ?? null);
70-
if ($type->isBuiltin() && !is_null($value)) {
72+
if ($type instanceof ReflectionUnionType || $type instanceof ReflectionIntersectionType) {
73+
$property->setValue($this, $value);
74+
} elseif ($type->isBuiltin() && !is_null($value)) {
7175
$property->setValue($this, $value);
7276
} elseif (PHP_VERSION_ID > 80100 && enum_exists($type->getName())) {
7377
$property->setValue($this, $value);

tests/Feature/DataTest.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,15 @@
3232
});
3333

3434
test('str', function () {
35+
$value = ['name' => 'hello'];
36+
$d = D::from($value);
37+
expect($d)->toBeInstanceOf(Data::class)
38+
->and($d->name)
39+
->toEqual($value['name']);
40+
});
41+
42+
43+
test('union type', function () {
3544
expect(Str::snake('HelloWorld'))->toBe('hello_world')
3645
->and(Str::camel('hello_world'))->toBe('helloWorld')
3746
->and(Str::camel(''))->toBe('')
@@ -66,4 +75,8 @@ class C extends Data
6675
enum enumA: string
6776
{
6877
case A = 'a';
78+
}
79+
80+
class D extends Data {
81+
public string|int $name;
6982
}

0 commit comments

Comments
 (0)