Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.2] Allow collections to be created from objects that implement Traversable #14628

Merged
merged 2 commits into from
Aug 5, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Countable;
use ArrayAccess;
use Traversable;
use ArrayIterator;
use CachingIterator;
use JsonSerializable;
Expand Down Expand Up @@ -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;
Expand Down
12 changes: 12 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1390,6 +1390,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
Expand Down