Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New when() helper. #52665

Merged
merged 15 commits into from
Sep 11, 2024
18 changes: 18 additions & 0 deletions src/Illuminate/Collections/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
14 changes: 14 additions & 0 deletions tests/Support/SupportHelpersTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down
Loading