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 'unless' method to collections (inverse of 'when') #19740

Merged
merged 1 commit into from
Jun 23, 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
13 changes: 13 additions & 0 deletions src/Illuminate/Support/Collection.php
Original file line number Diff line number Diff line change
Expand Up @@ -384,6 +384,19 @@ public function when($value, callable $callback, callable $default = null)
return $this;
}

/**
* Apply the callback if the value is falsy.
*
* @param bool $value
* @param callable $callback
* @param callable $default
* @return mixed
*/
public function unless($value, callable $callback, callable $default = null)
{
return $this->when(! $value, $callback, $default);
}

/**
* Filter items by the given key value pair.
*
Expand Down
32 changes: 32 additions & 0 deletions tests/Support/SupportCollectionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2121,6 +2121,38 @@ public function testWhenDefault()

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

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

$collection->unless(false, function ($collection) {
return $collection->push('caleb');
});

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

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

$collection->unless(true, function ($collection) {
return $collection->push('caleb');
});

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

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

$collection->unless(true, function ($collection) {
return $collection->push('caleb');
}, function ($collection) {
return $collection->push('taylor');
});

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

class TestSupportCollectionHigherOrderItem
Expand Down