Skip to content

Commit 4df8d3f

Browse files
committed
Allow closures when calling throw_if
1 parent e359739 commit 4df8d3f

File tree

2 files changed

+31
-2
lines changed

2 files changed

+31
-2
lines changed

src/Illuminate/Support/helpers.php

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -398,18 +398,23 @@ function tap($value, $callback = null)
398398
* Throw the given exception if the given condition is true.
399399
*
400400
* @template TValue
401+
* @template TParams of mixed
401402
* @template TException of \Throwable
402403
*
403404
* @param TValue $condition
404-
* @param TException|class-string<TException>|string $exception
405-
* @param mixed ...$parameters
405+
* @param TException|\Closure(TParams): mixed|class-string<TException>|string $exception
406+
* @param TParams ...$parameters
406407
* @return ($condition is true ? never : ($condition is non-empty-mixed ? never : TValue))
407408
*
408409
* @throws TException
409410
*/
410411
function throw_if($condition, $exception = 'RuntimeException', ...$parameters)
411412
{
412413
if ($condition) {
414+
if (is_callable($exception)) {
415+
$exception = $exception(...$parameters);
416+
}
417+
413418
if (is_string($exception) && class_exists($exception)) {
414419
$exception = new $exception(...$parameters);
415420
}

tests/Support/SupportHelpersTest.php

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -832,6 +832,30 @@ public function testThrowExceptionAsStringWithMessage()
832832
throw_if(true, LogicException::class, 'test');
833833
}
834834

835+
public function testThrowClosureException()
836+
{
837+
$this->expectException(\Exception::class);
838+
$this->expectExceptionMessage('test');
839+
840+
throw_if(true, fn () => new \Exception('test'));
841+
}
842+
843+
public function testThrowClosureWithParamsException()
844+
{
845+
$this->expectException(\Exception::class);
846+
$this->expectExceptionMessage('test');
847+
848+
throw_if(true, fn (string $message) => new \Exception($message), 'test');
849+
}
850+
851+
public function testThrowClosureStringWithParamsException()
852+
{
853+
$this->expectException(\Exception::class);
854+
$this->expectExceptionMessage('test');
855+
856+
throw_if(true, fn () => \Exception::class, 'test');
857+
}
858+
835859
public function testThrowUnless()
836860
{
837861
$this->expectException(LogicException::class);

0 commit comments

Comments
 (0)