Skip to content

Commit

Permalink
restore type-narrowing for throw_* helpers (#53154) (#53164)
Browse files Browse the repository at this point in the history
  • Loading branch information
crishoj authored Oct 15, 2024
1 parent 231091c commit ddfbbf0
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
4 changes: 2 additions & 2 deletions src/Illuminate/Support/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -393,7 +393,7 @@ function tap($value, $callback = null)
* @param TValue $condition
* @param TException|class-string<TException>|string $exception
* @param mixed ...$parameters
* @return ($condition is non-empty-mixed ? never : TValue)
* @return ($condition is true ? never : ($condition is non-empty-mixed ? never : TValue))
*
* @throws TException
*/
Expand Down Expand Up @@ -421,7 +421,7 @@ function throw_if($condition, $exception = 'RuntimeException', ...$parameters)
* @param TValue $condition
* @param TException|class-string<TException>|string $exception
* @param mixed ...$parameters
* @return ($condition is non-empty-mixed ? TValue : never)
* @return ($condition is false ? never : ($condition is non-empty-mixed ? TValue : never))
*
* @throws TException
*/
Expand Down
19 changes: 17 additions & 2 deletions types/Support/Helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,22 +41,37 @@
}));
assertType('Illuminate\Support\HigherOrderTapProxy', tap(new User()));

function testThrowIf(float|int $foo): void
function testThrowIf(float|int $foo, DateTime $bar = null): void
{
assertType('never', throw_if(true, Exception::class));
assertType('bool', throw_if(false, Exception::class));
assertType('false', throw_if(empty($foo)));
throw_if(is_float($foo));
assertType('int', $foo);
throw_if($foo == false);
assertType('int<min, -1>|int<1, max>', $foo);

// Truthy/falsey argument
throw_if($bar);
assertType('null', $bar);
assertType('null', throw_if(null, Exception::class));
assertType('string', throw_if('', Exception::class));
assertType('never', throw_if('foo', Exception::class));
}

function testThrowUnless(float|int $foo): void
function testThrowUnless(float|int $foo, DateTime $bar = null): void
{
assertType('bool', throw_unless(true, Exception::class));
assertType('never', throw_unless(false, Exception::class));
assertType('true', throw_unless(empty($foo)));
throw_unless(is_int($foo));
assertType('int', $foo);
throw_unless($foo == false);
assertType('0', $foo);
throw_unless($bar instanceof DateTime);
assertType('DateTime', $bar);

// Truthy/falsey argument
assertType('never', throw_unless(null, Exception::class));
assertType('never', throw_unless('', Exception::class));
assertType('string', throw_unless('foo', Exception::class));
Expand Down

0 comments on commit ddfbbf0

Please sign in to comment.