Skip to content

Commit 51888a8

Browse files
authored
[9.x] Traversable should have priority over JsonSerializable in EnumerateValues (#44456)
1 parent b7d9768 commit 51888a8

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

src/Illuminate/Collections/Traits/EnumeratesValues.php

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -980,12 +980,12 @@ protected function getArrayableItems($items)
980980
return $items->all();
981981
} elseif ($items instanceof Arrayable) {
982982
return $items->toArray();
983+
} elseif ($items instanceof Traversable) {
984+
return iterator_to_array($items);
983985
} elseif ($items instanceof Jsonable) {
984986
return json_decode($items->toJson(), true);
985987
} elseif ($items instanceof JsonSerializable) {
986988
return (array) $items->jsonSerialize();
987-
} elseif ($items instanceof Traversable) {
988-
return iterator_to_array($items);
989989
} elseif ($items instanceof UnitEnum) {
990990
return [$items];
991991
}

tests/Support/SupportCollectionTest.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,14 @@
1616
use Illuminate\Support\MultipleItemsFoundException;
1717
use Illuminate\Support\Str;
1818
use InvalidArgumentException;
19+
use IteratorAggregate;
1920
use JsonSerializable;
2021
use Mockery as m;
2122
use PHPUnit\Framework\TestCase;
2223
use ReflectionClass;
2324
use stdClass;
2425
use Symfony\Component\VarDumper\VarDumper;
26+
use Traversable;
2527
use UnexpectedValueException;
2628

2729
if (PHP_VERSION_ID >= 80100) {
@@ -622,6 +624,11 @@ public function testGetArrayableItems($collection)
622624
$array = $method->invokeArgs($data, [$items]);
623625
$this->assertSame(['foo'], $array);
624626

627+
$subject = [new stdClass, new stdClass];
628+
$items = new TestTraversableAndJsonSerializableObject($subject);
629+
$array = $method->invokeArgs($data, [$items]);
630+
$this->assertSame($subject, $array);
631+
625632
$items = new $collection(['foo' => 'bar']);
626633
$array = $method->invokeArgs($data, [$items]);
627634
$this->assertSame(['foo' => 'bar'], $array);
@@ -5592,6 +5599,26 @@ public function jsonSerialize(): string
55925599
}
55935600
}
55945601

5602+
class TestTraversableAndJsonSerializableObject implements IteratorAggregate, JsonSerializable
5603+
{
5604+
public $items;
5605+
5606+
public function __construct($items)
5607+
{
5608+
$this->items = $items;
5609+
}
5610+
5611+
public function getIterator(): Traversable
5612+
{
5613+
return new ArrayIterator($this->items);
5614+
}
5615+
5616+
public function jsonSerialize(): array
5617+
{
5618+
return json_decode(json_encode($this->items), true);
5619+
}
5620+
}
5621+
55955622
class TestCollectionMapIntoObject
55965623
{
55975624
public $value;

0 commit comments

Comments
 (0)