Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[11.x] Adds support for enums on mapInto collection method #51027

Merged
merged 4 commits into from
Apr 12, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/Illuminate/Collections/Traits/EnumeratesValues.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Illuminate\Support\Traits;

use BackedEnum;
use CachingIterator;
use Closure;
use Exception;
Expand Down Expand Up @@ -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));
}

Expand Down
6 changes: 6 additions & 0 deletions tests/Support/Enums.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,9 @@ enum TestBackedEnum: int
case A = 1;
case B = 2;
}

enum TestStringBackedEnum: string
{
case A = 'A';
case B = 'B';
}
26 changes: 26 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand Down