Skip to content

Commit 321da34

Browse files
[11.x] Adds support for enums on mapInto collection method (#51027)
* [11.x] Adds support for enums on `mapInto` collection method. * [11.x] Adds support for enums on `mapInto` collection method. * [11.x] Adds support for enums on `mapInto` collection method. * [11.x] Adds support for enums on `mapInto` collection method.
1 parent 641f5a6 commit 321da34

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

src/Illuminate/Collections/Traits/EnumeratesValues.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace Illuminate\Support\Traits;
44

5+
use BackedEnum;
56
use CachingIterator;
67
use Closure;
78
use Exception;
@@ -410,6 +411,10 @@ public function flatMap(callable $callback)
410411
*/
411412
public function mapInto($class)
412413
{
414+
if (is_subclass_of($class, BackedEnum::class)) {
415+
return $this->map(fn ($value, $key) => $class::from($value));
416+
}
417+
413418
return $this->map(fn ($value, $key) => new $class($value, $key));
414419
}
415420

tests/Support/Enums.php

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,3 +12,9 @@ enum TestBackedEnum: int
1212
case A = 1;
1313
case B = 2;
1414
}
15+
16+
enum TestStringBackedEnum: string
17+
{
18+
case A = 'A';
19+
case B = 'B';
20+
}

tests/Support/SupportCollectionTest.php

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2961,6 +2961,32 @@ public function testMapInto($collection)
29612961
$this->assertSame('second', $data->get(1)->value);
29622962
}
29632963

2964+
#[DataProvider('collectionClassProvider')]
2965+
public function testMapIntoWithIntBackedEnums($collection)
2966+
{
2967+
$data = new $collection([
2968+
1, 2,
2969+
]);
2970+
2971+
$data = $data->mapInto(TestBackedEnum::class);
2972+
2973+
$this->assertSame(TestBackedEnum::A, $data->get(0));
2974+
$this->assertSame(TestBackedEnum::B, $data->get(1));
2975+
}
2976+
2977+
#[DataProvider('collectionClassProvider')]
2978+
public function testMapIntoWithStringBackedEnums($collection)
2979+
{
2980+
$data = new $collection([
2981+
'A', 'B',
2982+
]);
2983+
2984+
$data = $data->mapInto(TestStringBackedEnum::class);
2985+
2986+
$this->assertSame(TestStringBackedEnum::A, $data->get(0));
2987+
$this->assertSame(TestStringBackedEnum::B, $data->get(1));
2988+
}
2989+
29642990
#[DataProvider('collectionClassProvider')]
29652991
public function testNth($collection)
29662992
{

0 commit comments

Comments
 (0)