Skip to content

Commit 1ee611f

Browse files
committed
Duplicate HasAttributes::getStorableEnumValue() to avoid BC break in method signature in Laravel 11
laravel/framework@8647dcf
1 parent 7cc5754 commit 1ee611f

File tree

1 file changed

+22
-1
lines changed

1 file changed

+22
-1
lines changed

src/Eloquent/Model.php

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
namespace MongoDB\Laravel\Eloquent;
66

7+
use BackedEnum;
78
use Carbon\CarbonInterface;
89
use DateTimeInterface;
910
use Illuminate\Contracts\Queue\QueueableCollection;
@@ -22,6 +23,7 @@
2223
use MongoDB\BSON\UTCDateTime;
2324
use MongoDB\Laravel\Query\Builder as QueryBuilder;
2425
use Stringable;
26+
use ValueError;
2527

2628
use function array_key_exists;
2729
use function array_keys;
@@ -38,10 +40,12 @@
3840
use function is_string;
3941
use function ltrim;
4042
use function method_exists;
43+
use function sprintf;
4144
use function str_contains;
4245
use function str_starts_with;
4346
use function strcmp;
4447
use function uniqid;
48+
use function var_export;
4549

4650
abstract class Model extends BaseModel
4751
{
@@ -704,7 +708,7 @@ protected function addCastAttributesToArray(array $attributes, array $mutatedAtt
704708
}
705709

706710
if ($this->isEnumCastable($key) && (! $castValue instanceof Arrayable)) {
707-
$castValue = $castValue !== null ? $this->getStorableEnumValue($castValue) : null;
711+
$castValue = $castValue !== null ? $this->getStorableEnumValueFromLaravel11($this->getCasts()[$key], $castValue) : null;
708712
}
709713

710714
if ($castValue instanceof Arrayable) {
@@ -717,6 +721,23 @@ protected function addCastAttributesToArray(array $attributes, array $mutatedAtt
717721
return $attributes;
718722
}
719723

724+
/**
725+
* Duplicate of {@see HasAttributes::getStorableEnumValue()} for Laravel 11 as the signature of the method has
726+
* changed in a non-backward compatible way.
727+
*
728+
* @todo Remove this method when support for Laravel 10 is dropped.
729+
*/
730+
private function getStorableEnumValueFromLaravel11($expectedEnum, $value)
731+
{
732+
if (! $value instanceof $expectedEnum) {
733+
throw new ValueError(sprintf('Value [%s] is not of the expected enum type [%s].', var_export($value, true), $expectedEnum));
734+
}
735+
736+
return $value instanceof BackedEnum
737+
? $value->value
738+
: $value->name;
739+
}
740+
720741
/**
721742
* Is a value a BSON type?
722743
*

0 commit comments

Comments
 (0)