Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Previously, it was not possible to instantiate objects that have properties with a union type:
This pull request adds a
$converter
to theField
attribute, which enables unions:Unfortunately, I had to increase the surface area of the library's API by making
Json::instantiateClass()
public. I'm still thinking about alternatives. Like instead of returning the final value, the converter (which would be a misnomer at this point) could just return the type as a string.Alternatives considered
Field
:#[Converter(BarBazUnion::class)] public Bar|Baz $value
It felt more readable adding it to the existing attribute, and I don't see any downsides.
This could be very wasteful, especially for large unions. Also, what if multiple members can be instantiated? Now the order of the members matters - which shouldn't matter.
Json
instantiate the object. This would avoid making Json::instantiateClass() public. Works for strings, integers, floats, null, bools and classes, but not (as easily) for arrays (lists and maps). We would have to either use strings likelist<Foo>
andarray<string, Foo>
, but they would have to be parsed. Or we could use something likeList::of(Foo::class)
andMap::of('string', Foo::class)
.Another option would be a hybrid:
#[Field(typeProvider: BarBazUnion::class, converter: MyTypeConverter::class)]
. But these kind of conflict with each other.Future scope