Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 2.5 addViolationAt deprecated, use buildViolation()

I have been following the cookbook on how to create a class constraint validator and right now I am at the point where I am about to add the violation in the validate() function.

However my IDE notifies me the functions addViolation() and addViolationAt() are deprecated.

Can someone point me in the right direction on how to use the Context\ExecutionContextInterface::buildViolation() function instead?

$this->context is an instance of Symfony\Component\Validator\ExecutionContext

class ProtocolClassValidator extends ConstraintValidator
{
    public function validate($protocol, Constraint $constraint)
    {
        if ($protocol->getFoo() != $protocol->getBar()) {
            $this->context->addViolationAt(
                'foo',
                $constraint->message,
                array(),
                null
            );
        }
    }
}

When changing the call $this->context->addViolationAt() to simply $this->context->buildViolation(), I get the following Exception:

UndefinedMethodException: Attempted to call method "buildViolation" on class "Symfony\Component\Validator\ExecutionContext" in stripped path line 23. Did you mean to call: "addViolation"?

and line 23 has the following code:

    $builder = $this->context->buildViolation($constraint->message)
    ->atPath('formField')
    ->addViolation();
like image 202
Ruben Avatar asked Aug 12 '14 12:08

Ruben


1 Answers

addViolation and addViolationAt are deprecated from 2.5 but won't be removed until 3.0 so they are still usable for a good time.

However... taken from the the UPGRADE FROM 2.x to 3.0 log...

The method addViolationAt() was removed. You should use buildViolation() instead:

Before:

$context->addViolationAt('property', 'The value {{ value }} is invalid.', array(
    '{{ value }}' => $invalidValue,
));

After:

$context->buildViolation('The value {{ value }} is invalid.')
    ->atPath('property')
    ->setParameter('{{ value }}', $invalidValue)
    ->addViolation();
));

With a bit more taken from Context/ExecutionContextInterface...

/**
 * Returns a builder for adding a violation with extended information.
 *
 * Call {@link ConstraintViolationBuilderInterface::addViolation()} to
 * add the violation when you're done with the configuration:
 *
 *     $context->buildViolation('Please enter a number between %min% and %max.')
 *         ->setParameter('%min%', 3)
 *         ->setParameter('%max%', 10)
 *         ->setTranslationDomain('number_validation')
 *         ->addViolation();
 *
 * @param string $message    The error message
 * @param array  $parameters The parameters substituted in the error message
 *
 * @return ConstraintViolationBuilderInterface The violation builder
 */
public function buildViolation($message, array $parameters = array());
like image 197
qooplmao Avatar answered Oct 08 '22 23:10

qooplmao