Skip to content

Commit

Permalink
[5.2] Allow collections to be created from objects that implement Tra…
Browse files Browse the repository at this point in the history
…versable (#14628)

* Allow collections to be created from objects that implement Traversable

* Style fix; remove exta space character
  • Loading branch information
timsweb authored and taylorotwell committed Aug 5, 2016
1 parent 1f8c090 commit 01cf96f
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
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

0 comments on commit 01cf96f

Please sign in to comment.