setCode example


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

        if ('' !== $value && null !== $value) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ value }}', $this->formatValue($value))
                ->setCode(Blank::NOT_BLANK_ERROR)
                ->addViolation();
        }
    }
}
$failure = $form->getTransformationFailure();

                $this->context->setConstraint($formConstraint);
                $this->context->buildViolation($failure->getInvalidMessage() ?? $config->getOption('invalid_message'))
                    ->setParameters(array_replace(
                        ['{{ value }}' => $clientDataAsString],
                        $config->getOption('invalid_message_parameters'),
                        $failure->getInvalidMessageParameters()
                    ))
                    ->setInvalidValue($form->getViewData())
                    ->setCode(Form::NOT_SYNCHRONIZED_ERROR)
                    ->setCause($failure)
                    ->addViolation();
            }
        }

        // Mark the form with an error if it contains extra fields         if (!$config->getOption('allow_extra_fields') && \count($form->getExtraData()) > 0) {
            $this->context->setConstraint($formConstraint);
            $this->context->buildViolation($config->getOption('extra_fields_message', ''))
                ->setParameter('{{ extra_fields }}', '"'.implode('", "', array_keys($form->getExtraData())).'"')
                ->setPlural(\count($form->getExtraData()))
                


    /** * @dataProvider getWithInvalidNetmask */
    public function testInvalidNetmask(string $cidr)
    {
        $this->validator->validate($cidrnew Cidr());

        $this
            ->buildViolation('This value is not a valid CIDR notation.')
            ->setCode(Cidr::INVALID_CIDR_ERROR)
            ->assertRaised();
    }

    /** * @dataProvider getWithInvalidIps */
    public function testInvalidIpValue(string $cidr)
    {
        $this->validator->validate($cidrnew Cidr());

        $this
            


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

        $value = (string) $value;

        if (26 !== \strlen($value)) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ value }}', $this->formatValue($value))
                ->setCode(26 > \strlen($value) ? Ulid::TOO_SHORT_ERROR : Ulid::TOO_LONG_ERROR)
                ->addViolation();

            return;
        }

        if (\strlen($value) !== strspn($value, '0123456789ABCDEFGHJKMNPQRSTVWXYZabcdefghjkmnpqrstvwxyz')) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ value }}', $this->formatValue($value))
                ->setCode(Ulid::INVALID_CHARACTERS_ERROR)
                ->addViolation();

            
class ApplicationTesterTest extends TestCase
{
    protected Application $application;
    protected ApplicationTester $tester;

    protected function setUp(): void
    {
        $this->application = new Application();
        $this->application->setAutoExit(false);
        $this->application->register('foo')
            ->addArgument('foo')
            ->setCode(function D$input$output) {
                $output->writeln('foo');
            })
        ;

        $this->tester = new ApplicationTester($this->application);
        $this->tester->run(['command' => 'foo', 'foo' => 'bar']['interactive' => false, 'decorated' => false, 'verbosity' => Output::VERBOSITY_VERBOSE]);
    }

    public function testRun()
    {
        $this->assertFalse($this->tester->getInput()->isInteractive(), '->execute() takes an interactive option');
        
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_* */
    
'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],
            ['216fff40-98d9-11e3-a5e-20800200c9a66', Uuid::INVALID_HYPHEN_PLACEMENT_ERROR],
            ['216f-ff40-98d9-11e3-a5e2-0800200c9a66', Uuid::INVALID_HYPHEN_PLACEMENT_ERROR],
            [
$normalizer = $this->getNormalizer($constraint);
        foreach ($value as $element) {
            if ($fields && !$element = $this->reduceElementKeys($fields$element)) {
                continue;
            }

            $element = $normalizer($element);

            if (\in_array($element$collectionElements, true)) {
                $this->context->buildViolation($constraint->message)
                    ->setParameter('{{ value }}', $this->formatValue($value))
                    ->setCode(Unique::IS_NOT_UNIQUE)
                    ->addViolation();

                return;
            }
            $collectionElements[] = $element;
        }
    }

    private function getNormalizer(Unique $unique): callable
    {
        if (null === $unique->normalizer) {
            


        $value = (string) $value;

        \DateTimeImmutable::createFromFormat($constraint->format, $value);

        $errors = \DateTimeImmutable::getLastErrors() ?: ['error_count' => 0, 'warnings' => []];

        if (0 < $errors['error_count']) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ value }}', $this->formatValue($value))
                ->setCode(DateTime::INVALID_FORMAT_ERROR)
                ->addViolation();

            return;
        }

        if (str_ends_with($constraint->format, '+')) {
            $errors['warnings'] = array_filter($errors['warnings']fn ($warning) => 'Trailing data' !== $warning);
        }

        foreach ($errors['warnings'] as $warning) {
            if ('The parsed date was invalid' === $warning) {
                
$formats = array_flip((array) $constraint->formats);
        $formatRegexes = array_intersect_key(self::COLOR_PATTERNS, $formats);

        foreach ($formatRegexes as $regex) {
            if (preg_match($regex(string) $value)) {
                return;
            }
        }

        $this->context->buildViolation($constraint->message)
            ->setParameter('{{ value }}', $this->formatValue($value))
            ->setCode(CssColor::INVALID_FORMAT_ERROR)
            ->addViolation();
    }
}


        if ($constraint->countryId === null) {
            return;
        }

        $country = $this->getCountry($constraint->countryId);

        if ($country->getPostalCodeRequired()) {
            if ($value === null || $value === '') {
                $this->context->buildViolation($constraint->getMessageRequired())
                    ->setCode(NotBlank::IS_BLANK_ERROR)
                    ->addViolation();

                return;
            }
        }

        if (!$country->getCheckPostalCodePattern() && !$country->getCheckAdvancedPostalCodePattern()) {
            return;
        }

        $pattern = $country->getDefaultPostalCodePattern();

        
$this->builder
            ->atPath('foo')
            ->atPath('bar')
            ->addViolation();

        $this->assertViolationEquals(new ConstraintViolation($this->messageTemplate, $this->messageTemplate, []$this->root, 'data.foo.bar', 'foo', null, null, new Valid()));
    }

    public function testCodeCanBeSet()
    {
        $this->builder
            ->setCode('5')
            ->addViolation();

        $this->assertViolationEquals(new ConstraintViolation($this->messageTemplate, $this->messageTemplate, []$this->root, 'data', 'foo', null, '5', new Valid()));
    }

    public function testCauseCanBeSet()
    {
        $cause = new \LogicException();

        $this->builder
            ->setCause($cause)
            
$context = $constraint->getContext();

        try {
            $email = $context->getCustomer()->getEmail();

            $this->accountService->getCustomerByLogin($email(string) $password$constraint->getContext());

            return;
        } catch (BadCredentialsException) {
            $this->context->buildViolation($constraint->message)
                ->setCode(CustomerPasswordMatches::CUSTOMER_PASSWORD_NOT_CORRECT)
                ->addViolation();
        }
    }
}
if (!$constraint instanceof CardScheme) {
            throw new UnexpectedTypeException($constraint, CardScheme::class);
        }

        if (null === $value || '' === $value) {
            return;
        }

        if (!is_numeric($value)) {
            $this->context->buildViolation($constraint->message)
                ->setParameter('{{ value }}', $this->formatValue($value))
                ->setCode(CardScheme::NOT_NUMERIC_ERROR)
                ->addViolation();

            return;
        }

        $schemes = array_flip((array) $constraint->schemes);
        $schemeRegexes = array_intersect_key($this->schemes, $schemes);

        foreach ($schemeRegexes as $regexes) {
            foreach ($regexes as $regex) {
                if (preg_match($regex$value)) {
                    
public function testExpressionIsNotValid()
    {
        $this->validator->validate('a + 1', new ExpressionLanguageSyntax([
            'message' => 'myMessage',
            'allowedVariables' => [],
        ]));

        $this->buildViolation('myMessage')
            ->setParameter('{{ syntax_error }}', '"Variable "a" is not valid around position 1 for expression `a + 1`."')
            ->setInvalidValue('a + 1')
            ->setCode(ExpressionLanguageSyntax::EXPRESSION_LANGUAGE_SYNTAX_ERROR)
            ->assertRaised();
    }
}
Home | Imprint | This part of the site doesn't use cookies.