diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index 9c7ee76..4ba71af 100644 --- a/src/Illuminate/Support/Collection.php +++ b/src/Illuminate/Support/Collection.php @@ -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. * diff --git a/tests/Support/SupportCollectionTest.php b/tests/Support/SupportCollectionTest.php index 59be6b0..60e4c21 100644 --- a/tests/Support/SupportCollectionTest.php +++ b/tests/Support/SupportCollectionTest.php @@ -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