Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow disabling default Optional values in CreationContext #931

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

ragulka
Copy link
Contributor

@ragulka ragulka commented Jan 15, 2025

DTOs that have properties using the Optional type can be a little painful to work with when creating the DTO in a context where you'd rather have a missing value be resolved to null. This can happen when preparing a DTO on the server-side, later to be converted to a JSON payload. For instance, when an Eloquent model is converted to array, it may not include all the keys for the DTO - which would result in Optional type being used for the matching properties.

This PR makes it possible to control whether the DefaultValuesPipeline will set properties that support the Optional type to Optional, or fall back to null (if allowed by the property).

See the docs diff for usage.

@rubenvanassche
Copy link
Member

Can you add a tests which checks that indeed the optional value is replaced with null and also checks what happens when the option is on and we've got a type like string|Optional which doesn't support Optional?

@ragulka
Copy link
Contributor Author

ragulka commented Jan 18, 2025

Can you add a tests which checks that indeed the optional value is replaced with null and also checks what happens when the option is on and we've got a type like string|Optional which doesn't support Optional?

@rubenvanassche sure thing - added in b22cc7b.

Note that when using string|Optional, the property will end up not being set. When converting such DTO to array, it will simply exclude that property from the array - which I believe is to be expected.

However, the property must not be accessed before initialization, or PHP will throw an error:

Error: Typed property SongData::$slug must not be accessed before initialization

This might throw off some, so I've added a warning to docs about this as well..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants