Skip to content

Commit

Permalink
[11.x] add lazy default to when helper (#52747)
Browse files Browse the repository at this point in the history
* add lazy default to when helper

* Update helpers.php

---------

Co-authored-by: Taylor Otwell <[email protected]>
  • Loading branch information
rodrigopedra and taylorotwell authored Sep 12, 2024
1 parent def4668 commit 982710a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 10 deletions.
11 changes: 6 additions & 5 deletions src/Illuminate/Collections/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -239,18 +239,19 @@ function value($value, ...$args)

if (! function_exists('when')) {
/**
* Output a value if the given condition is true.
* Return a value if the given condition is true.
*
* @param mixed $condition
* @param \Closure|mixed $output
* @param \Closure|mixed $value
* @param \Closure|mixed $default
* @return mixed
*/
function when($condition, $output)
function when($condition, $value, $default = null)
{
if ($condition) {
return value($output);
return value($value, $condition);
}

return null;
return value($default, $condition);
}
}
18 changes: 13 additions & 5 deletions tests/Support/SupportHelpersTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -103,15 +103,23 @@ public function testClassBasename()
public function testWhen()
{
$this->assertEquals('Hello', when(true, 'Hello'));
$this->assertEquals(null, when(false, 'Hello'));
$this->assertNull(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->assertNull(when(1 == 2, 'There'));
$this->assertNull(when('1', fn () => null));
$this->assertNull(when(0, fn () => null));
$this->assertEquals('True', when([1, 2, 3, 4], 'True')); // Array
$this->assertEquals(null, when([], 'True')); // Empty Array = Falsy
$this->assertNull(when([], 'True')); // Empty Array = Falsy
$this->assertEquals('True', when(new StdClass, fn () => 'True')); // Object
$this->assertEquals('World', when(false, 'Hello', 'World'));
$this->assertEquals('World', when(1 === 0, 'Hello', 'World')); // strict types
$this->assertEquals('World', when(1 == '0', 'Hello', 'World')); // loose types
$this->assertNull(when('', fn () => 'There', fn () => null));
$this->assertNull(when(0, fn () => 'There', fn () => null));
$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
}

public function testFilled()
Expand Down

0 comments on commit 982710a

Please sign in to comment.