Skip to content

Commit

Permalink
Merge pull request #43 from nutgram/fix-null-for-enum-cast
Browse files Browse the repository at this point in the history
Fix null for enum cast
  • Loading branch information
sergix44 authored Jul 16, 2024
2 parents cdd8cb9 + 8519679 commit ff827df
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/Hydrator.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ public function hydrate(string|object $object, array|object $data): object
$propertyType = $resolver->resolve(
$key,
$propertyType->getTypes(),
is_array($data[$key]) ? $data[$key] : $data
isset($data[$key]) && is_array($data[$key]) ? $data[$key] : $data
);
} else {
throw new Exception\UnsupportedPropertyTypeException(sprintf(
Expand Down
1 change: 1 addition & 0 deletions src/Resolver/EnumOrScalar.php
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ public function resolve(string $propertyName, array $propertyTypes, array $data)
'integer' => 'int',
'double' => 'float',
'boolean' => 'bool',
'NULL' => 'null',
default => $valueType,
};

Expand Down
11 changes: 11 additions & 0 deletions tests/Fixtures/ObjectWithStringableEnumNullableUnion.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?php

namespace SergiX44\Hydrator\Tests\Fixtures;

use SergiX44\Hydrator\Resolver\EnumOrScalar;

final class ObjectWithStringableEnumNullableUnion
{
#[EnumOrScalar]
public StringableEnum|string|null $value = null;
}
14 changes: 14 additions & 0 deletions tests/HydratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -541,6 +541,20 @@ public function testHydrateStringableEnumUnionPropertyFloat(): void
$this->assertSame(.23, $object->value);
}

public function testHydrateStringableEnumUnionPropertyNull(): void
{
$object = (new Hydrator())->hydrate(Fixtures\ObjectWithStringableEnumNullableUnion::class, ['value' => null]);

$this->assertNull($object->value);
}

public function testHydrateStringableEnumUnionPropertyNullNonSet(): void
{
$object = (new Hydrator())->hydrate(Fixtures\ObjectWithStringableEnumNullableUnion::class, []);

$this->assertNull($object->value);
}

public function testHydrateStringableEnumUnionPropertyBool(): void
{
$this->expectException(Exception\UnsupportedPropertyTypeException::class);
Expand Down

0 comments on commit ff827df

Please sign in to comment.