Skip to content

Commit

Permalink
Add 'unless' method to collections (inverse of 'when') (#19740)
Browse files Browse the repository at this point in the history
  • Loading branch information
calebporzio authored and taylorotwell committed Jun 23, 2017
1 parent 75554ce commit 4bae8a4
Show file tree
Hide file tree
Showing 2 changed files with 45 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 @@ -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

0 comments on commit 4bae8a4

Please sign in to comment.