Symfony 2.5 addViolation不推荐使用,使用buildViolation()

时间:2014-08-12 12:57:32

标签: php validation symfony

我一直在关注如何创建类约束验证器的cookbook,现在我正准备在validate()函数中添加违规。

但是我的IDE通知我,addViolation()addViolationAt()已弃用。

有人能指出我如何使用Context\ExecutionContextInterface::buildViolation()功能的正确方向吗?

$this->contextSymfony\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
            );
        }
    }
}

将来电$this->context->addViolationAt()更改为$this->context->buildViolation()时,我收到以下例外情况:

  

UndefinedMethodException:尝试调用方法" buildViolation"上   class" Symfony \ Component \ Validator \ ExecutionContext"在   剥离路径   第23行。您的意思是:" addViolation"?

和第23行具有以下代码:

    $builder = $this->context->buildViolation($constraint->message)
    ->atPath('formField')
    ->addViolation();

1 个答案:

答案 0 :(得分:20)

addViolationaddViolationAt已从2.5弃用,但在3.0之前不会删除,因此它们仍然可以使用一段时间。

但是......取自UPGRADE FROM 2.x to 3.0日志......

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();
));

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());