Skip to content

Commit 3cf02fa

Browse files
michaeldyryndataylorotwell
authored andcommitted
Add a when method to Collection (#17917)
1 parent 2095064 commit 3cf02fa

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

src/Illuminate/Support/Collection.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -308,6 +308,22 @@ public function filter(callable $callback = null)
308308
return new static(array_filter($this->items));
309309
}
310310

311+
/**
312+
* Apply the callback if the value is truthy.
313+
*
314+
* @param bool $value
315+
* @param callable $callback
316+
* @return mixed
317+
*/
318+
public function when($value, callable $callback)
319+
{
320+
if ($value) {
321+
return $callback($this);
322+
}
323+
324+
return $this;
325+
}
326+
311327
/**
312328
* Filter items by the given key value pair.
313329
*

tests/Support/SupportCollectionTest.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1895,6 +1895,25 @@ public function testTap()
18951895
$this->assertSame([1], $fromTap);
18961896
$this->assertSame([1, 2, 3], $collection->toArray());
18971897
}
1898+
1899+
public function testWhen()
1900+
{
1901+
$collection = new Collection(['michael', 'tom']);
1902+
1903+
$collection->when(true, function ($collection) {
1904+
return $collection->push('adam');
1905+
});
1906+
1907+
$this->assertSame(['michael', 'tom', 'adam'], $collection->toArray());
1908+
1909+
$collection = new Collection(['michael', 'tom']);
1910+
1911+
$collection->when(false, function ($collection) {
1912+
return $collection->push('adam');
1913+
});
1914+
1915+
$this->assertSame(['michael', 'tom'], $collection->toArray());
1916+
}
18981917
}
18991918

19001919
class TestSupportCollectionHigherOrderItem

0 commit comments

Comments
 (0)