Skip to content

Commit

Permalink
Add Collection::wrap method (#20055)
Browse files Browse the repository at this point in the history
If the given value is not a collection, wrap it in one.

If you pass a collection or an array as the value you get a collection with data in the collection or array back. If you pass in anything else you get a collection of one containing that value.
  • Loading branch information
thecrypticace authored and taylorotwell committed Jul 14, 2017
1 parent f111352 commit f57b9e2
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,19 @@ public static function make($items = [])
return new static($items);
}

/**
* If the given value is not a collection, wrap it in one.
*
* @param mixed $value
* @return static
*/
public static function wrap($value)
{
return $value instanceof self
? new static($value)
: new static(Arr::wrap($value));
}

/**
* Create a new collection by invoking the callback a given amount of times.
*
Expand Down
48 changes: 48 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1014,6 +1014,49 @@ public function testMakeMethodFromArray()
$this->assertEquals(['foo' => 'bar'], $collection->all());
}

public function testWrapWithScalar()
{
$collection = Collection::wrap('foo');
$this->assertEquals(['foo'], $collection->all());
}

public function testWrapWithArray()
{
$collection = Collection::wrap(['foo']);
$this->assertEquals(['foo'], $collection->all());
}

public function testWrapWithArrayable()
{
$collection = Collection::wrap($o = new TestArrayableObject);
$this->assertEquals([$o], $collection->all());
}

public function testWrapWithJsonable()
{
$collection = Collection::wrap($o = new TestJsonableObject);
$this->assertEquals([$o], $collection->all());
}

public function testWrapWithJsonSerialize()
{
$collection = Collection::wrap($o = new TestJsonSerializeObject);
$this->assertEquals([$o], $collection->all());
}

public function testWrapWithCollectionClass()
{
$collection = Collection::wrap(Collection::make(['foo']));
$this->assertEquals(['foo'], $collection->all());
}

public function testWrapWithCollectionSubclass()
{
$collection = TestCollectionSubclass::wrap(Collection::make(['foo']));
$this->assertEquals(['foo'], $collection->all());
$this->assertInstanceOf(TestCollectionSubclass::class, $collection);
}

public function testTimesMethod()
{
$two = Collection::times(2, function ($number) {
Expand Down Expand Up @@ -2287,3 +2330,8 @@ public function __construct($value)
$this->value = $value;
}
}

class TestCollectionSubclass extends Collection
{
//
}

0 comments on commit f57b9e2

Please sign in to comment.