From d5a23bfd217defc1748a802ff0b9b239d7f5bd52 Mon Sep 17 00:00:00 2001 From: Bruno Alod Date: Tue, 4 Oct 2022 15:17:59 -0300 Subject: [PATCH] [9.x] Traversable should have priority over JsonSerializable in EnumerateValues --- .../Collections/Traits/EnumeratesValues.php | 4 +-- tests/Support/SupportCollectionTest.php | 27 +++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/Illuminate/Collections/Traits/EnumeratesValues.php b/src/Illuminate/Collections/Traits/EnumeratesValues.php index 80da8c3d4e08..25facc2d3add 100644 --- a/src/Illuminate/Collections/Traits/EnumeratesValues.php +++ b/src/Illuminate/Collections/Traits/EnumeratesValues.php @@ -980,12 +980,12 @@ protected function getArrayableItems($items) return $items->all(); } elseif ($items instanceof Arrayable) { return $items->toArray(); + } elseif ($items instanceof Traversable) { + return iterator_to_array($items); } elseif ($items instanceof Jsonable) { return json_decode($items->toJson(), true); } elseif ($items instanceof JsonSerializable) { return (array) $items->jsonSerialize(); - } elseif ($items instanceof Traversable) { - return iterator_to_array($items); } elseif ($items instanceof UnitEnum) { return [$items]; } diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 2d0cab7eefb8..30a80d4c7867 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -16,12 +16,14 @@ use Illuminate\Support\MultipleItemsFoundException; use Illuminate\Support\Str; use InvalidArgumentException; +use IteratorAggregate; use JsonSerializable; use Mockery as m; use PHPUnit\Framework\TestCase; use ReflectionClass; use stdClass; use Symfony\Component\VarDumper\VarDumper; +use Traversable; use UnexpectedValueException; if (PHP_VERSION_ID >= 80100) { @@ -622,6 +624,11 @@ public function testGetArrayableItems($collection) $array = $method->invokeArgs($data, [$items]); $this->assertSame(['foo'], $array); + $subject = [new stdClass, new stdClass]; + $items = new TestTraversableAndJsonSerializableObject($subject); + $array = $method->invokeArgs($data, [$items]); + $this->assertSame($subject, $array); + $items = new $collection(['foo' => 'bar']); $array = $method->invokeArgs($data, [$items]); $this->assertSame(['foo' => 'bar'], $array); @@ -5592,6 +5599,26 @@ public function jsonSerialize(): string } } +class TestTraversableAndJsonSerializableObject implements IteratorAggregate, JsonSerializable +{ + public $items; + + public function __construct($items) + { + $this->items = $items; + } + + public function getIterator(): Traversable + { + return new ArrayIterator($this->items); + } + + public function jsonSerialize(): array + { + return json_decode(json_encode($this->items), true); + } +} + class TestCollectionMapIntoObject { public $value;