From 5989bae0f177a22975b862414006930e250dc047 Mon Sep 17 00:00:00 2001 From: Caleb White Date: Tue, 1 Oct 2024 09:37:14 -0500 Subject: [PATCH] feat: narrow types for throw_if and throw_unless --- src/Illuminate/Support/helpers.php | 4 ++-- types/Support/Helpers.php | 23 +++++++++++++++++++++-- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/src/Illuminate/Support/helpers.php b/src/Illuminate/Support/helpers.php index d46bf6ffcfd3..b7f3a33a1199 100644 --- a/src/Illuminate/Support/helpers.php +++ b/src/Illuminate/Support/helpers.php @@ -393,7 +393,7 @@ function tap($value, $callback = null) * @param TValue $condition * @param TException|class-string|string $exception * @param mixed ...$parameters - * @return TValue + * @return ($condition is true ? never : TValue) * * @throws TException */ @@ -421,7 +421,7 @@ function throw_if($condition, $exception = 'RuntimeException', ...$parameters) * @param TValue $condition * @param TException|class-string|string $exception * @param mixed ...$parameters - * @return TValue + * @return ($condition is true ? TValue : never) * * @throws TException */ diff --git a/types/Support/Helpers.php b/types/Support/Helpers.php index 80f8a27f9d0e..9542aecfac95 100644 --- a/types/Support/Helpers.php +++ b/types/Support/Helpers.php @@ -41,9 +41,28 @@ })); assertType('Illuminate\Support\HigherOrderTapProxy', tap(new User())); -assertType('bool', throw_if(true, Exception::class)); -assertType('bool', throw_unless(true, Exception::class)); +function testThrowIf(float|int $foo): 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|int<1, max>', $foo); +} + +function testThrowUnless(float|int $foo): 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); +} assertType('int', transform('filled', fn () => 1, true)); assertType('int', transform(['filled'], fn () => 1));