diff --git a/src/Illuminate/Collections/helpers.php b/src/Illuminate/Collections/helpers.php index 4150c38ef621..58dcecfb1452 100644 --- a/src/Illuminate/Collections/helpers.php +++ b/src/Illuminate/Collections/helpers.php @@ -236,3 +236,21 @@ function value($value, ...$args) return $value instanceof Closure ? $value(...$args) : $value; } } + +if (! function_exists('when')) { + /** + * Output a value if the given condition is true. + * + * @param mixed $condition + * @param \Closure|mixed $output + * @return mixed + */ + function when($condition, $output) + { + if ($condition) { + return value($output); + } + + return null; + } +} diff --git a/tests/Support/SupportHelpersTest.php b/tests/Support/SupportHelpersTest.php index 234385e38e12..69877bfb3a2a 100644 --- a/tests/Support/SupportHelpersTest.php +++ b/tests/Support/SupportHelpersTest.php @@ -100,6 +100,20 @@ public function testClassBasename() $this->assertSame('..', class_basename('\Foo\Bar\Baz\\..\\')); } + public function testWhen() + { + $this->assertEquals('Hello', when(true, 'Hello')); + $this->assertEquals(null, when(false, 'Hello')); + $this->assertEquals('There', when(1 === 1, 'There')); // strict types + $this->assertEquals('There', when(1 == '1', 'There')); // loose types + $this->assertEquals(null, when(1 == 2, 'There')); + $this->assertEquals(null, when('1', fn () => null)); + $this->assertEquals(null, when(0, fn () => null)); + $this->assertEquals('True', when([1, 2, 3, 4], 'True')); // Array + $this->assertEquals(null, when([], 'True')); // Empty Array = Falsy + $this->assertEquals('True', when(new StdClass, fn () => 'True')); // Object + } + public function testFilled() { $this->assertFalse(filled(null));