createIsValidCallable example


final class Validation
{
    /** * Creates a callable chain of constraints. */
    public static function createCallable(Constraint|ValidatorInterface $constraintOrValidator = null, Constraint ...$constraints): callable
    {
        $validator = self::createIsValidCallable($constraintOrValidator, ...$constraints);

        return static function D$value) use ($validator) {
            if (!$validator($value$violations)) {
                throw new ValidationFailedException($value$violations);
            }

            return $value;
        };
    }

    /** * Creates a callable that returns true/false instead of throwing validation exceptions. * * @return callable(mixed $value, ConstraintViolationListInterface &$violations = null): bool */
 catch (ValidationFailedException $e) {
            $this->assertEquals('test', $e->getValue());

            $violations = $e->getViolations();
            $this->assertCount(1, $violations);
            $this->assertEquals('This value should be blank.', $violations->get(0)->getMessage());
        }
    }

    public function testCreateIsValidCallableValid()
    {
        $validator = Validation::createIsValidCallable(new NotBlank());
        $this->assertTrue($validator('test@example.com'));
    }

    public function testCreateIsValidCallableInvalid()
    {
        $validator = Validation::createIsValidCallable(new Blank());
        $this->assertFalse($validator('test', $violations));
        $this->assertCount(1, $violations);
        $this->assertEquals('This value should be blank.', $violations->get(0)->getMessage());
    }
}

final class Validation
{
    /** * Creates a callable chain of constraints. */
    public static function createCallable(Constraint|ValidatorInterface $constraintOrValidator = null, Constraint ...$constraints): callable
    {
        $validator = self::createIsValidCallable($constraintOrValidator, ...$constraints);

        return static function D$value) use ($validator) {
            if (!$validator($value$violations)) {
                throw new ValidationFailedException($value$violations);
            }

            return $value;
        };
    }

    /** * Creates a callable that returns true/false instead of throwing validation exceptions. * * @return callable(mixed $value, ConstraintViolationListInterface &$violations = null): bool */
Home | Imprint | This part of the site doesn't use cookies.