diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index a6a7927..5ce9484 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; @@ -1241,6 +1242,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 fe7b71b..6077046 100644 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -1354,6 +1354,54 @@ public function testWithMultipleModeValues() $collection = new Collection([1, 2, 2, 1]); $this->assertEquals([1, 2], $collection->mode()); } + + public function testSliceOffset() + { + $collection = new Collection([1, 2, 3, 4, 5, 6, 7, 8]); + $this->assertEquals([4, 5, 6, 7, 8], $collection->slice(3)->values()->toArray()); + } + + public function testSliceNegativeOffset() + { + $collection = new Collection([1, 2, 3, 4, 5, 6, 7, 8]); + $this->assertEquals([6, 7, 8], $collection->slice(-3)->values()->toArray()); + } + + public function testSliceOffsetAndLength() + { + $collection = new Collection([1, 2, 3, 4, 5, 6, 7, 8]); + $this->assertEquals([4, 5, 6], $collection->slice(3, 3)->values()->toArray()); + } + + public function testSliceOffsetAndNegativeLength() + { + $collection = new Collection([1, 2, 3, 4, 5, 6, 7, 8]); + $this->assertEquals([4, 5, 6, 7], $collection->slice(3, -1)->values()->toArray()); + } + + public function testSliceNegativeOffsetAndLength() + { + $collection = new Collection([1, 2, 3, 4, 5, 6, 7, 8]); + $this->assertEquals([4, 5, 6], $collection->slice(-5, 3)->values()->toArray()); + } + + 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