\Jawira\TheLostFunctions\throw_unless

throw_unless - Throws an exception unless provided expression evaluates to true.

Description

throw_unless(mixed $expression, ?Throwable $throwable = null): mixed

This function can replace assert() function. Unlike assert(), throw_unless() cannot be disabled.

Parameters

expression
Any valid PHP expression.
throwable
An optional throwable object. If not provided \Exception will be used.

Return value

If you passed a value as parameter, then the same value will be returned. If you used an expression $expression, the result of the expression will be returned.

Example

I wanted to use assert() this way:

assert($user instanceof \App\Entity\User, new Exception('Invalid user'));

Because assert can be disabled, I had to rewrite the code:

if(!($user instanceof \App\Entity\User)) {
    throw new Exception('Invalid user');
}

Using throw_unless() I can write this in a single line again:

use function Jawira\TheLostFunctions\throw_unless;

throw_unless($user instanceof \App\Entity\User, new Exception('Invalid user'));