diff --git a/src/Illuminate/Collections/Traits/EnumeratesValues.php b/src/Illuminate/Collections/Traits/EnumeratesValues.php index 041f80c080a7..1b0f63fdf048 100644 --- a/src/Illuminate/Collections/Traits/EnumeratesValues.php +++ b/src/Illuminate/Collections/Traits/EnumeratesValues.php @@ -2,6 +2,7 @@ namespace Illuminate\Support\Traits; +use BackedEnum; use CachingIterator; use Closure; use Exception; @@ -410,6 +411,10 @@ public function flatMap(callable $callback) */ public function mapInto($class) { + if (is_subclass_of($class, BackedEnum::class)) { + return $this->map(fn ($value, $key) => $class::from($value)); + } + return $this->map(fn ($value, $key) => new $class($value, $key)); } diff --git a/tests/Support/Enums.php b/tests/Support/Enums.php index 45fc07da52f5..3d31e55321c6 100644 --- a/tests/Support/Enums.php +++ b/tests/Support/Enums.php @@ -12,3 +12,9 @@ enum TestBackedEnum: int case A = 1; case B = 2; } + +enum TestStringBackedEnum: string +{ + case A = 'A'; + case B = 'B'; +} diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 3edff0c35f96..7e2565044c72 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -2961,6 +2961,32 @@ public function testMapInto($collection) $this->assertSame('second', $data->get(1)->value); } + #[DataProvider('collectionClassProvider')] + public function testMapIntoWithIntBackedEnums($collection) + { + $data = new $collection([ + 1, 2, + ]); + + $data = $data->mapInto(TestBackedEnum::class); + + $this->assertSame(TestBackedEnum::A, $data->get(0)); + $this->assertSame(TestBackedEnum::B, $data->get(1)); + } + + #[DataProvider('collectionClassProvider')] + public function testMapIntoWithStringBackedEnums($collection) + { + $data = new $collection([ + 'A', 'B', + ]); + + $data = $data->mapInto(TestStringBackedEnum::class); + + $this->assertSame(TestStringBackedEnum::A, $data->get(0)); + $this->assertSame(TestStringBackedEnum::B, $data->get(1)); + } + #[DataProvider('collectionClassProvider')] public function testNth($collection) {