Crell / Serde

Robust Serde (serialization/deserialization) library for PHP 8.
Other
299 stars 14 forks source link

Can't deserialize nullable Enum #66

Closed nuvalis closed 4 months ago

nuvalis commented 4 months ago

In EnumExport there is no handling of a nullable Enum which will cause the string backed Enum::from() to throw an exception https://github.com/Crell/Serde/blob/a3229d7a4c98861b186abf06802f6740d4b7d9cd/src/PropertyHandler/EnumExporter.php#L35

Example

class MyClassDTO {
    private ?ServiceTypeEnum $internalServiceType = null;
}

$data = [
    'internalServiceType' => null
];

$serde = new SerdeCommon();
$serde->deserialize($data, from: 'array', to: MyClassDTO::class);
TypeError : App\Services\Delivery\ServiceTypeEnum::from(): Argument #1 ($value) must be of type string, null given
vendor/crell/serde/src/PropertyHandler/EnumExporter.php:54

I tried adding this after the match case, which solved my issue

// src/PropertyHandler/EnumExporter.php

if ($field->nullable && $val === null) {
    return $val;
}
Crell commented 4 months ago

You are correct, good catch. Fixed now.