fix(laravel): detect enum casts in eloquent property metadata factory#8247
Merged
Conversation
Map Laravel enum casts (BackedEnum and UnitEnum) to Type::enum() instead of falling back to Type::string(). Resolves missing enum schema and normalization downstream (JsonSchema, OpenAPI) when models declare casts via $casts or the casts() method. Fixes api-platform#8138
PHP's ReflectionClass::newInstanceWithoutConstructor() throws \Error (not \ReflectionException) for enums. When the GraphQl TypeConverter resolves an enum property (e.g. an Eloquent cast to BackedEnum) it walks the resource metadata factory chain, hitting EloquentResourceCollectionMetadataFactory and crashing. Guard with $refl->isEnum() before newInstanceWithoutConstructor() in both EloquentResourceCollectionMetadataFactory and the symmetric EloquentAttributePropertyMetadataFactory, returning the decorated chain's result for the enum class. Adds a unit test that exercises the path with workbench BookStatus. Refs api-platform#8138.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Summary
Laravel models declaring enum casts (
'col' => MyEnum::classin$castsorcasts()) lost enum metadata:EloquentPropertyMetadataFactoryfell through toType::string(). Downstream JSON Schema / OpenAPI / normalization saw a string, not an enum. Now resolves toType::enum($class)when the cast target is aBackedEnumorUnitEnum, also handling Laravel'sClass:paramparameter syntax (e.g.AsEnumCollection:Foo).Reproduction
A model with
protected \$casts = ['status' => BookStatus::class]exposedstatusas a plain string in the generated schema instead of an enum.Test plan
Fixes #8138