From 13ebafac4d928e826d1fa52c35a7c84ec583a8ee Mon Sep 17 00:00:00 2001 From: Jamie Date: Mon, 23 Dec 2024 12:09:27 +0000 Subject: [PATCH] when() accept callable first parameter --- src/Illuminate/Collections/helpers.php | 2 ++ tests/Support/SupportHelpersTest.php | 2 ++ 2 files changed, 4 insertions(+) diff --git a/src/Illuminate/Collections/helpers.php b/src/Illuminate/Collections/helpers.php index 6d691f5e3091..55844559e711 100644 --- a/src/Illuminate/Collections/helpers.php +++ b/src/Illuminate/Collections/helpers.php @@ -248,6 +248,8 @@ function value($value, ...$args) */ function when($condition, $value, $default = null) { + $condition = $condition instanceof Closure ? $condition() : $condition; + if ($condition) { return value($value, $condition); } diff --git a/tests/Support/SupportHelpersTest.php b/tests/Support/SupportHelpersTest.php index ee4c09a73101..55fef4e85369 100644 --- a/tests/Support/SupportHelpersTest.php +++ b/tests/Support/SupportHelpersTest.php @@ -134,6 +134,8 @@ public function testWhen() $this->assertEquals('False', when([], 'True', 'False')); // Empty Array = Falsy $this->assertTrue(when(true, fn ($value) => $value, fn ($value) => ! $value)); // lazy evaluation $this->assertTrue(when(false, fn ($value) => $value, fn ($value) => ! $value)); // lazy evaluation + $this->assertEquals('Hello', when(fn () => true, 'Hello')); // lazy evaluation condition + $this->assertEquals('World', when(fn () => false, 'Hello', 'World')); // lazy evaluation condition } public function testFilled()