From ddfbbf03847afc1fd706d3d8287ffc3d05300bda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Christian=20Rish=C3=B8j?= Date: Tue, 15 Oct 2024 15:42:42 +0200 Subject: [PATCH] restore type-narrowing for `throw_*` helpers (#53154) (#53164) --- src/Illuminate/Support/helpers.php | 4 ++-- types/Support/Helpers.php | 19 +++++++++++++++++-- 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/Illuminate/Support/helpers.php b/src/Illuminate/Support/helpers.php index 5abe5befd5b0..7e2b3d9bc570 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 ($condition is non-empty-mixed ? never : TValue) + * @return ($condition is true ? never : ($condition is non-empty-mixed ? 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 ($condition is non-empty-mixed ? TValue : never) + * @return ($condition is false ? never : ($condition is non-empty-mixed ? TValue : never)) * * @throws TException */ diff --git a/types/Support/Helpers.php b/types/Support/Helpers.php index d0201de6172d..30f0f44c5b7c 100644 --- a/types/Support/Helpers.php +++ b/types/Support/Helpers.php @@ -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|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));