Skip to content

Commit 6dab6db

Browse files
committed
Add getStorableEnumValue
1 parent 932cf99 commit 6dab6db

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

src/Concerns/HasCasts.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
use Illuminate\Support\Str;
1818
use InvalidArgumentException;
1919
use UnitEnum;
20+
use ValueError;
2021

2122
/** @mixin Model */
2223
trait HasCasts
@@ -143,6 +144,20 @@ protected function setEnumCastableAttribute(string $key, mixed $value): void
143144
}
144145
}
145146

147+
/**
148+
* Get the storable value from the given enum.
149+
*/
150+
protected function getStorableEnumValue(string $expectedEnum, UnitEnum|BackedEnum $value): string|int
151+
{
152+
if (! $value instanceof $expectedEnum) {
153+
throw new ValueError(sprintf('Value [%s] is not of the expected enum type [%s].', var_export($value, true), $expectedEnum));
154+
}
155+
156+
return $value instanceof BackedEnum
157+
? $value->value
158+
: $value->name;
159+
}
160+
146161
/**
147162
* Determine if the cast type is a custom date time cast.
148163
*/

0 commit comments

Comments
 (0)