From 43e804af0e716b0676bb97d71307cc94cc48b0cf Mon Sep 17 00:00:00 2001 From: Michael Dyrynda Date: Tue, 14 Feb 2017 11:23:06 +1030 Subject: [PATCH] Add a when method to Collection --- src/Illuminate/Support/Collection.php | 16 ++++++++++++++++ tests/Support/SupportCollectionTest.php | 19 +++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/src/Illuminate/Support/Collection.php b/src/Illuminate/Support/Collection.php index 9c7ee7669fcc..4ba71af8610a 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 59be6b0d4290..60e4c21f3995 100755 --- 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