Skip to content

Commit

Permalink
New when() helper. (#52665)
Browse files Browse the repository at this point in the history
* feat(blade): New @when directive.

* StyleCI

* fix: move to compilesConditionals + remove default expression

* fix: styleCI

* fix: when() returns the value, rather than echoing it.

* fix: Remove @throws tags

* fix: styleCI

* fix: escaping on by default

* fix: remove blade directive and adds tests for when helper

* StyleCI

* remove default, add more tests.

* Remove return type

* StyleCI

* Update helpers.php

* move function

---------

Co-authored-by: Taylor Otwell <[email protected]>
  • Loading branch information
danmatthews and taylorotwell authored Sep 11, 2024
1 parent c65725d commit d9c322d
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
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

0 comments on commit d9c322d

Please sign in to comment.