Skip to content

Commit e404e88

Browse files
authored
Handle collection creation around a single enum (#42839)
* Handle collection creation around a single enum * Test collections from enum * Use import
1 parent fee60a1 commit e404e88

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

src/Illuminate/Collections/Traits/EnumeratesValues.php

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
use Symfony\Component\VarDumper\VarDumper;
1717
use Traversable;
1818
use UnexpectedValueException;
19+
use UnitEnum;
1920

2021
/**
2122
* @property-read HigherOrderCollectionProxy $average
@@ -991,6 +992,8 @@ protected function getArrayableItems($items)
991992
return (array) $items->jsonSerialize();
992993
} elseif ($items instanceof Traversable) {
993994
return iterator_to_array($items);
995+
} elseif ($items instanceof UnitEnum) {
996+
return [$items];
994997
}
995998

996999
return (array) $items;

tests/Support/Enums.php

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<?php
2+
3+
namespace Illuminate\Tests\Support;
4+
5+
enum TestEnum
6+
{
7+
case A;
8+
}
9+
10+
enum TestBackedEnum: int
11+
{
12+
case A = 1;
13+
}

tests/Support/SupportCollectionTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,10 @@
2424
use Symfony\Component\VarDumper\VarDumper;
2525
use UnexpectedValueException;
2626

27+
if (PHP_VERSION_ID >= 80100) {
28+
include_once 'Enums.php';
29+
}
30+
2731
class SupportCollectionTest extends TestCase
2832
{
2933
/**
@@ -4254,6 +4258,26 @@ public function testCollectionFromTraversableWithKeys($collection)
42544258
$this->assertEquals(['foo' => 1, 'bar' => 2, 'baz' => 3], $data->toArray());
42554259
}
42564260

4261+
/**
4262+
* @dataProvider collectionClassProvider
4263+
* @requires PHP >= 8.1
4264+
*/
4265+
public function testCollectionFromEnum($collection)
4266+
{
4267+
$data = new $collection(TestEnum::A);
4268+
$this->assertEquals([TestEnum::A], $data->toArray());
4269+
}
4270+
4271+
/**
4272+
* @dataProvider collectionClassProvider
4273+
* @requires PHP >= 8.1
4274+
*/
4275+
public function testCollectionFromBackedEnum($collection)
4276+
{
4277+
$data = new $collection(TestBackedEnum::A);
4278+
$this->assertEquals([TestBackedEnum::A], $data->toArray());
4279+
}
4280+
42574281
/**
42584282
* @dataProvider collectionClassProvider
42594283
*/

0 commit comments

Comments
 (0)