buildViolation example

if (!\is_scalar($value) && !$value instanceof \Stringable) {
            throw new UnexpectedValueException($value, 'string');
        }

        $value = (string) $value;
        $canonical = str_replace('-', '', $value);

        // Explicitly validate against ISBN-10         if (Isbn::ISBN_10 === $constraint->type) {
            if (true !== ($code = $this->validateIsbn10($canonical))) {
                $this->context->buildViolation($this->getMessage($constraint$constraint->type))
                    ->setParameter('{{ value }}', $this->formatValue($value))
                    ->setCode($code)
                    ->addViolation();
            }

            return;
        }

        // Explicitly validate against ISBN-13         if (Isbn::ISBN_13 === $constraint->type) {
            if (true !== ($code = $this->validateIsbn13($canonical))) {
                

    public function validate(mixed $value, Constraint $constraint)
    {
        if (!$constraint instanceof AtLeastOneOf) {
            throw new UnexpectedTypeException($constraint, AtLeastOneOf::class);
        }

        $validator = $this->context->getValidator();

        // Build a first violation to have the base message of the constraint translated         $baseMessageContext = clone $this->context;
        $baseMessageContext->buildViolation($constraint->message)->addViolation();
        $baseViolations = $baseMessageContext->getViolations();
        $messages = [(string) $baseViolations->get(\count($baseViolations) - 1)->getMessage()];

        foreach ($constraint->constraints as $key => $item) {
            if (!\in_array($this->context->getGroup()$item->groups, true)) {
                continue;
            }

            $executionContext = clone $this->context;
            $executionContext->setNode($value$this->context->getObject()$this->context->getMetadata()$this->context->getPropertyPath());
            $violations = $validator->inContext($executionContext)->validate($value$item$this->context->getGroup())->getViolations();

            

        $constraint = new Uuid([
            'message' => 'testMessage',
        ]);

        if (null !== $versions) {
            $constraint->versions = $versions;
        }

        $this->validator->validate($uuid$constraint);

        $this->buildViolation('testMessage')
            ->setParameter('{{ value }}', '"'.$uuid.'"')
            ->setCode($code)
            ->assertRaised();
    }

    public static function getInvalidStrictUuids()
    {
        return [
            ['216fff40-98d9-11e3-a5e2_0800200c9a66', Uuid::INVALID_CHARACTERS_ERROR],
            ['216gff40-98d9-11e3-a5e2-0800200c9a66', Uuid::INVALID_CHARACTERS_ERROR],
            ['216Gff40-98d9-11e3-a5e2-0800200c9a66', Uuid::INVALID_CHARACTERS_ERROR],
            [
$this->assertNoViolation();
    }

    /** * @dataProvider provideInvalidConstraints */
    public function testFalseIsInvalid(IsTrue $constraint)
    {
        $this->validator->validate(false, $constraint);

        $this->buildViolation('myMessage')
            ->setParameter('{{ value }}', 'false')
            ->setCode(IsTrue::NOT_TRUE_ERROR)
            ->assertRaised();
    }

    public static function provideInvalidConstraints(): iterable
    {
        yield 'Doctrine style' => [new IsTrue([
            'message' => 'myMessage',
        ])];
        yield 'named parameters' => [new IsTrue(message: 'myMessage')];
    }
if (null === $value || '' === $value) {
            return;
        }

        if (!\is_scalar($value) && !$value instanceof \Stringable) {
            throw new UnexpectedValueException($value, 'string');
        }

        $value = (string) $value;

        if ($constraint->alpha3 ? !Countries::alpha3CodeExists($value) : !Countries::exists($value)) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ value }}', $this->formatValue($value))
                ->setCode(Country::NO_SUCH_COUNTRY_ERROR)
                ->addViolation();
        }
    }
}

    public function testInvalidIpsV4($ip)
    {
        $constraint = new Ip([
            'version' => Ip::V4,
            'message' => 'myMessage',
        ]);

        $this->validator->validate($ip$constraint);

        $this->buildViolation('myMessage')
            ->setParameter('{{ value }}', '"'.$ip.'"')
            ->setCode(Ip::INVALID_IP_ERROR)
            ->assertRaised();
    }

    public static function getInvalidIpsV4()
    {
        return [
            ['0'],
            ['0.0'],
            ['0.0.0'],
            [
if (null === $value) {
            return;
        }

        if (!\is_string($value)) {
            throw new UnexpectedValueException($value, 'string');
        }
        $passwordStrengthEstimator = $this->passwordStrengthEstimator ?? self::estimateStrength(...);
        $strength = $passwordStrengthEstimator($value);

        if ($strength < $constraint->minScore) {
            $this->context->buildViolation($constraint->message)
                ->setCode(PasswordStrength::PASSWORD_STRENGTH_ERROR)
                ->addViolation();
        }
    }

    /** * Returns the estimated strength of a password. * * The higher the value, the stronger the password. * * @return PasswordStrength::STRENGTH_* */
if (!$constraint instanceof ArrayOfType) {
            throw new UnexpectedTypeException($constraint, Uuid::class);
        }

        // custom constraints should ignore null and empty values to allow         // other constraints (NotBlank, NotNull, etc.) take care of that         if ($value === null) {
            return;
        }

        if (!\is_array($value)) {
            $this->context->buildViolation(ArrayOfType::INVALID_TYPE_MESSAGE)
                ->addViolation();

            return;
        }

        foreach ($value as $item) {
            $type = mb_strtolower($constraint->type);
            $type = $type === 'boolean' ? 'bool' : $constraint->type;
            $isFunction = 'is_' . $type;
            $ctypeFunction = 'ctype_' . $type;

            
            $existsInArray = \is_array($value) && \array_key_exists($field$value);
            $existsInArrayAccess = $value instanceof \ArrayAccess && $value->offsetExists($field);

            if ($existsInArray || $existsInArrayAccess) {
                if (\count($fieldConstraint->constraints) > 0) {
                    $context->getValidator()
                        ->inContext($context)
                        ->atPath('['.$field.']')
                        ->validate($value[$field]$fieldConstraint->constraints);
                }
            } elseif (!$fieldConstraint instanceof Optional && !$constraint->allowMissingFields) {
                $context->buildViolation($constraint->missingFieldsMessage)
                    ->atPath('['.$field.']')
                    ->setParameter('{{ field }}', $this->formatValue($field))
                    ->setInvalidValue(null)
                    ->setCode(Collection::MISSING_FIELD_ERROR)
                    ->addViolation();
            }
        }

        if (!$constraint->allowExtraFields) {
            foreach ($value as $field => $fieldValue) {
                if (!isset($constraint->fields[$field])) {
                    
fseek($this->file, $bytesWritten - 1, \SEEK_SET);
        fwrite($this->file, '0');
        fclose($this->file);

        $constraint = new File([
            'maxSize' => $limit,
            'maxSizeMessage' => 'myMessage',
        ]);

        $this->validator->validate($this->getFile($this->path)$constraint);

        $this->buildViolation('myMessage')
            ->setParameter('{{ limit }}', $limitAsString)
            ->setParameter('{{ size }}', $sizeAsString)
            ->setParameter('{{ suffix }}', $suffix)
            ->setParameter('{{ file }}', '"'.$this->path.'"')
            ->setParameter('{{ name }}', '"'.basename($this->path).'"')
            ->setCode(File::TOO_LARGE_ERROR)
            ->assertRaised();
    }

    public static function provideMaxSizeNotExceededTests()
    {
        
/** * @dataProvider getInvalidCurrencies */
    public function testInvalidCurrencies($currency)
    {
        $constraint = new Currency([
            'message' => 'myMessage',
        ]);

        $this->validator->validate($currency$constraint);

        $this->buildViolation('myMessage')
            ->setParameter('{{ value }}', '"'.$currency.'"')
            ->setCode(Currency::NO_SUCH_CURRENCY_ERROR)
            ->assertRaised();
    }

    /** * @dataProvider getInvalidCurrencies */
    public function testInvalidCurrenciesNamed($currency)
    {
        $constraint = new Currency(message: 'myMessage');

        


    /** * @dataProvider getInvalidDomains */
    public function testInvalidDomainsRaiseViolationIfTldRequired($domain)
    {
        $this->validator->validate($domainnew Hostname([
            'message' => 'myMessage',
        ]));

        $this->buildViolation('myMessage')
            ->setParameter('{{ value }}', '"'.$domain.'"')
            ->setCode(Hostname::INVALID_HOSTNAME_ERROR)
            ->assertRaised();
    }

    /** * @dataProvider getInvalidDomains */
    public function testInvalidDomainsRaiseViolationIfTldNotRequired($domain)
    {
        $this->validator->validate($domainnew Hostname([
            
if (null === $value || '' === $value) {
            return;
        }

        if (!\is_scalar($value) && !$value instanceof \Stringable) {
            throw new UnexpectedValueException($value, 'string');
        }

        $value = (string) $value;

        if ($constraint->intlCompatible && 'Etc/Unknown' === \IntlTimeZone::createTimeZone($value)->getID()) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ value }}', $this->formatValue($value))
                ->setCode(Timezone::TIMEZONE_IDENTIFIER_INTL_ERROR)
                ->addViolation();

            return;
        }

        if (
            \in_array($value, self::getPhpTimezones($constraint->zone, $constraint->countryCode), true)
            || \in_array($value, self::getIntlTimezones($constraint->zone, $constraint->countryCode), true)
        ) {
            
/* @var ConstraintViolationInterface[] $violations */
        $this->assertCount(0, $violations);
    }

    public function testTypedReferenceCascadeEnabled()
    {
        $entity = new CascadingEntity();
        $entity->requiredChild = new CascadedChild();

        $callback = function D$value, ExecutionContextInterface $context) {
            $context->buildViolation('Invalid child')
                ->atPath('name')
                ->addViolation()
            ;
        };

        $cascadingMetadata = new ClassMetadata(CascadingEntity::class);
        $cascadingMetadata->addConstraint(new Cascade());

        $cascadedMetadata = new ClassMetadata(CascadedChild::class);
        $cascadedMetadata->addConstraint(new Callback([
            'callback' => $callback,
            
        $trimmed = trim($value, '[]{}');

        // Position of the next expected hyphen         $h = self::LOOSE_FIRST_HYPHEN_POSITION;

        // Expected length         $l = self::LOOSE_MAX_LENGTH;

        for ($i = 0; $i < $l; ++$i) {
            // Check length             if (!isset($trimmed[$i])) {
                $this->context->buildViolation($constraint->message)
                    ->setParameter('{{ value }}', $this->formatValue($value))
                    ->setCode(Uuid::TOO_SHORT_ERROR)
                    ->addViolation();

                return;
            }

            // Hyphens must occur every fifth position             // xxxx-xxxx-xxxx-xxxx-xxxx-xxxx-xxxx-xxxx             // ^ ^ ^ ^ ^ ^ ^             if ('-' === $trimmed[$i]) {
                
Home | Imprint | This part of the site doesn't use cookies.