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.4] Add when method to collections #17917

Merged
merged 1 commit into from
Feb 14, 2017
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
16 changes: 16 additions & 0 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,22 @@ public function filter(callable $callback = null)
return new static(array_filter($this->items));
}

/**
* Apply the callback if the value is truthy.
*
* @param bool $value
* @param callable $callback
* @return mixed
*/
public function when($value, callable $callback)
{
if ($value) {
return $callback($this);
}

return $this;
}

/**
* Filter items by the given key value pair.
*
Expand Down
19 changes: 19 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1895,6 +1895,25 @@ public function testTap()
$this->assertSame([1], $fromTap);
$this->assertSame([1, 2, 3], $collection->toArray());
}

public function testWhen()
{
$collection = new Collection(['michael', 'tom']);

$collection->when(true, function ($collection) {
return $collection->push('adam');
});

$this->assertSame(['michael', 'tom', 'adam'], $collection->toArray());

$collection = new Collection(['michael', 'tom']);

$collection->when(false, function ($collection) {
return $collection->push('adam');
});

$this->assertSame(['michael', 'tom'], $collection->toArray());
}
}

class TestSupportCollectionHigherOrderItem
Expand Down