From 6f6a72024671c85a70e7105169c77710dc35c8fa Mon Sep 17 00:00:00 2001 From: Tim Williams Date: Fri, 5 Aug 2016 15:49:58 +0100 Subject: [PATCH] [5.2] Allow collections to be created from objects that implement Traversable (#14628) * Allow collections to be created from objects that implement Traversable * Style fix; remove exta space character --- src/Illuminate/Support/Collection.php | 3 +++ tests/Support/SupportCollectionTest.php | 12 ++++++++++++ 2 files changed, 15 insertions(+) diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index 1e341b39c57e..9e741f4e6509 100644 --- a/src/Illuminate/Support/Collection.php +++ b/src/Illuminate/Support/Collection.php @@ -4,6 +4,7 @@ use Countable; use ArrayAccess; +use Traversable; use ArrayIterator; use CachingIterator; use JsonSerializable; @@ -1267,6 +1268,8 @@ protected function getArrayableItems($items) return json_decode($items->toJson(), true); } elseif ($items instanceof JsonSerializable) { return $items->jsonSerialize(); + } elseif ($items instanceof Traversable) { + return iterator_to_array($items); } return (array) $items; diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 7745400ecbc9..ea8c1adcb213 100755 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -1467,6 +1467,18 @@ public function testSliceNegativeOffsetAndNegativeLength() $collection = new Collection([1, 2, 3, 4, 5, 6, 7, 8]); $this->assertEquals([3, 4, 5, 6], $collection->slice(-6, -2)->values()->toArray()); } + + public function testCollectonFromTraversable() + { + $collection = new Collection(new \ArrayObject([1, 2, 3])); + $this->assertEquals([1, 2, 3], $collection->toArray()); + } + + public function testCollectonFromTraversableWithKeys() + { + $collection = new Collection(new \ArrayObject(['foo' => 1, 'bar' => 2, 'baz' => 3])); + $this->assertEquals(['foo' => 1, 'bar' => 2, 'baz' => 3], $collection->toArray()); + } } class TestAccessorEloquentTestStub