Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support to return false when an assertion fails #331

Open
luxferoo opened this issue Dec 2, 2022 · 1 comment
Open

Support to return false when an assertion fails #331

luxferoo opened this issue Dec 2, 2022 · 1 comment

Comments

@luxferoo
Copy link

luxferoo commented Dec 2, 2022

This is my suggestion to support returning false in case of failure :

 public static function notEmpty($value, $message = null, string $propertyPath = null): bool
 {
        if (empty($value)) {
            $message = \sprintf(
                static::generateMessage($message ?: 'Value "%s" is empty, but non empty value was expected.'),
                static::stringify($value)
            );

            // throw static::createException($value, $message, static::VALUE_EMPTY, $propertyPath);
            return static::handleFailure($value, $message, static::VALUE_EMPTY, $propertyPath);
        }

        return true;
  }
 protected static function handleFailure($value, $message, $code, $propertyPath = null, array $constraints = []): bool
 {
        $exceptionClass = static::$exceptionClass;

        throw new $exceptionClass($message, $code, $propertyPath, $value, $constraints);
 }

That way anyone can inherit from Assertion class and override handleFailure to return false instead of throwing an exception. This is helpfull in many situations for example for a ternary condition...

@luxferoo luxferoo changed the title More flexibility to support false as a result instead of exception Support to return false when an assertion fails Dec 2, 2022
@luxferoo
Copy link
Author

luxferoo commented Jan 9, 2023

@beberlei 🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant