Skip to content

Commit ff827df

Browse files
authored
Merge pull request #43 from nutgram/fix-null-for-enum-cast
Fix null for enum cast
2 parents cdd8cb9 + 8519679 commit ff827df

File tree

4 files changed

+27
-1
lines changed

4 files changed

+27
-1
lines changed

src/Hydrator.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ public function hydrate(string|object $object, array|object $data): object
118118
$propertyType = $resolver->resolve(
119119
$key,
120120
$propertyType->getTypes(),
121-
is_array($data[$key]) ? $data[$key] : $data
121+
isset($data[$key]) && is_array($data[$key]) ? $data[$key] : $data
122122
);
123123
} else {
124124
throw new Exception\UnsupportedPropertyTypeException(sprintf(

src/Resolver/EnumOrScalar.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ public function resolve(string $propertyName, array $propertyTypes, array $data)
3939
'integer' => 'int',
4040
'double' => 'float',
4141
'boolean' => 'bool',
42+
'NULL' => 'null',
4243
default => $valueType,
4344
};
4445

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<?php
2+
3+
namespace SergiX44\Hydrator\Tests\Fixtures;
4+
5+
use SergiX44\Hydrator\Resolver\EnumOrScalar;
6+
7+
final class ObjectWithStringableEnumNullableUnion
8+
{
9+
#[EnumOrScalar]
10+
public StringableEnum|string|null $value = null;
11+
}

tests/HydratorTest.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -541,6 +541,20 @@ public function testHydrateStringableEnumUnionPropertyFloat(): void
541541
$this->assertSame(.23, $object->value);
542542
}
543543

544+
public function testHydrateStringableEnumUnionPropertyNull(): void
545+
{
546+
$object = (new Hydrator())->hydrate(Fixtures\ObjectWithStringableEnumNullableUnion::class, ['value' => null]);
547+
548+
$this->assertNull($object->value);
549+
}
550+
551+
public function testHydrateStringableEnumUnionPropertyNullNonSet(): void
552+
{
553+
$object = (new Hydrator())->hydrate(Fixtures\ObjectWithStringableEnumNullableUnion::class, []);
554+
555+
$this->assertNull($object->value);
556+
}
557+
544558
public function testHydrateStringableEnumUnionPropertyBool(): void
545559
{
546560
$this->expectException(Exception\UnsupportedPropertyTypeException::class);

0 commit comments

Comments
 (0)