text column to support PHP Enum casting #4633
Closed
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.
WHY
BEFORE - What was wrong? What was happening before this PR?
Some of us do this in our model casts to take advantage of PHP 8.1 Enums to ensure a given column can only contain a set of specific values
protected $casts = [
'status' => StatusEnum::class
]
But in backpack it will be an error
mb_strwidth(): Argument #1 ($string) must be of type string
AFTER - What is happening after this PR?
Display the enum value
HOW
How did you achieve that, in technical terms?
1st we use the function_exists('enum_exists') check, then if that functions exist, we know we are at least on a PHP version that supports PHP enums and check if the value is an instance of UnitEnum, if it is then we call ->value to get the enum value
This is how i see laravel support PHP Enums currently. See Line 26
https://github.com/laravel/framework/blob/0f1eb9ef9d3846eeca0e6bfac77ddd67ce8ca12b/src/Illuminate/Database/Eloquent/Relations/Concerns/InteractsWithDictionary.php#L26
Additionally, concepts like toString() does not exist for PHP Enums (they are not allowed to implement Stringable interface). So we have to handle it at the column view file level (or maybe at the level before it is passed to the column/field blade file)
Is it a breaking change?
No
How can we test the before & after?
Cast a text column to php enum and use the text column