CuyZ / Valinor

PHP library that helps to map any input into a strongly-typed value object structure.

Home Page:https://valinor.cuyz.io

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Not existent (optional) fields vs nullable fields

szado opened this issue · comments

commented

I've encountered an issue with creating an API resource for partial updates, where a field in DTO (hydrating by Valinor) can be either passed and updated with the provided value or not passed (or set to null) and skipped during the update. However, the problem arises when null is a valid value for a field. In that case, when the user sends a null value (or does not send it at all) during the update, there is ambiguity whether they want to skip the field or clear it.

Is there any recommended way to handle such a case, or does it require additional handling on the library side?

commented

I resolved this problem by creating custom class (called Undefined in my case) and using it as default value for parameters which I care about distinction between undefined in source or equals null.

Example:
public readonly Color | null | Undefined $color = new Undefined(),

Hi @szado, I'm glad you solved your issue.

I do not see a better way to handle such usecase, keep me updated if you find a problem with this particular solution. 😉

What about a #[MayBeUndefined] property attribute that tells the mapper to leave the property uninitialized if not present (instead of throwing)? The Undefined works, but I feel like this is a common use case.