Skip to content

Commit 4bae8a4

Browse files
calebporziotaylorotwell
authored andcommitted
Add 'unless' method to collections (inverse of 'when') (#19740)
1 parent 75554ce commit 4bae8a4

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

src/Illuminate/Support/Collection.php

+13
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,19 @@ public function when($value, callable $callback, callable $default = null)
384384
return $this;
385385
}
386386

387+
/**
388+
* Apply the callback if the value is falsy.
389+
*
390+
* @param bool $value
391+
* @param callable $callback
392+
* @param callable $default
393+
* @return mixed
394+
*/
395+
public function unless($value, callable $callback, callable $default = null)
396+
{
397+
return $this->when(! $value, $callback, $default);
398+
}
399+
387400
/**
388401
* Filter items by the given key value pair.
389402
*

tests/Support/SupportCollectionTest.php

+32
Original file line numberDiff line numberDiff line change
@@ -2121,6 +2121,38 @@ public function testWhenDefault()
21212121

21222122
$this->assertSame(['michael', 'tom', 'taylor'], $collection->toArray());
21232123
}
2124+
2125+
public function testUnless()
2126+
{
2127+
$collection = new Collection(['michael', 'tom']);
2128+
2129+
$collection->unless(false, function ($collection) {
2130+
return $collection->push('caleb');
2131+
});
2132+
2133+
$this->assertSame(['michael', 'tom', 'caleb'], $collection->toArray());
2134+
2135+
$collection = new Collection(['michael', 'tom']);
2136+
2137+
$collection->unless(true, function ($collection) {
2138+
return $collection->push('caleb');
2139+
});
2140+
2141+
$this->assertSame(['michael', 'tom'], $collection->toArray());
2142+
}
2143+
2144+
public function testUnlessDefault()
2145+
{
2146+
$collection = new Collection(['michael', 'tom']);
2147+
2148+
$collection->unless(true, function ($collection) {
2149+
return $collection->push('caleb');
2150+
}, function ($collection) {
2151+
return $collection->push('taylor');
2152+
});
2153+
2154+
$this->assertSame(['michael', 'tom', 'taylor'], $collection->toArray());
2155+
}
21242156
}
21252157

21262158
class TestSupportCollectionHigherOrderItem

0 commit comments

Comments
 (0)