beberlei / assert

Thin assertion library for use in libraries and business-model
Other
2.41k stars 186 forks source link

Support to return false when an assertion fails #331

Open luxferoo opened 1 year ago

luxferoo commented 1 year ago

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 commented 1 year ago

@beberlei 🙏