Skip to content

Commit

Permalink
Handle collection creation around a single enum (#42839)
Browse files Browse the repository at this point in the history
* Handle collection creation around a single enum

* Test collections from enum

* Use import
  • Loading branch information
tontonsb authored Jun 17, 2022
1 parent fee60a1 commit e404e88
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/Illuminate/Collections/Traits/EnumeratesValues.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Symfony\Component\VarDumper\VarDumper;
use Traversable;
use UnexpectedValueException;
use UnitEnum;

/**
* @property-read HigherOrderCollectionProxy $average
Expand Down Expand Up @@ -991,6 +992,8 @@ protected function getArrayableItems($items)
return (array) $items->jsonSerialize();
} elseif ($items instanceof Traversable) {
return iterator_to_array($items);
} elseif ($items instanceof UnitEnum) {
return [$items];
}

return (array) $items;
Expand Down
13 changes: 13 additions & 0 deletions tests/Support/Enums.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<?php

namespace Illuminate\Tests\Support;

enum TestEnum
{
case A;
}

enum TestBackedEnum: int
{
case A = 1;
}
24 changes: 24 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@
use Symfony\Component\VarDumper\VarDumper;
use UnexpectedValueException;

if (PHP_VERSION_ID >= 80100) {
include_once 'Enums.php';
}

class SupportCollectionTest extends TestCase
{
/**
Expand Down Expand Up @@ -4254,6 +4258,26 @@ public function testCollectionFromTraversableWithKeys($collection)
$this->assertEquals(['foo' => 1, 'bar' => 2, 'baz' => 3], $data->toArray());
}

/**
* @dataProvider collectionClassProvider
* @requires PHP >= 8.1
*/
public function testCollectionFromEnum($collection)
{
$data = new $collection(TestEnum::A);
$this->assertEquals([TestEnum::A], $data->toArray());
}

/**
* @dataProvider collectionClassProvider
* @requires PHP >= 8.1
*/
public function testCollectionFromBackedEnum($collection)
{
$data = new $collection(TestBackedEnum::A);
$this->assertEquals([TestBackedEnum::A], $data->toArray());
}

/**
* @dataProvider collectionClassProvider
*/
Expand Down

0 comments on commit e404e88

Please sign in to comment.