Rub*_*ben 7 php validation symfony
我一直在关注如何创建类约束验证器的烹饪书,现在我正处于我要在validate()函数中添加违规的程度.
但是我的IDE通知我函数addViolation()并且addViolationAt()已被弃用.
有人能指出我如何使用该Context\ExecutionContextInterface::buildViolation()功能的正确方向吗?
$this->context 是一个实例 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
);
}
}
}
Run Code Online (Sandbox Code Playgroud)
将调用更改$this->context->addViolationAt()为简单时$this->context->buildViolation(),我得到以下异常:
UndefinedMethodException:尝试在剥离的路径 行23中的类"Symfony\Component\Validator\ExecutionContext"上调用方法"buildViolation" .您是否要调用:"addViolation"?
第23行具有以下代码:
$builder = $this->context->buildViolation($constraint->message)
->atPath('formField')
->addViolation();
Run Code Online (Sandbox Code Playgroud)
qoo*_*mao 22
addViolation并且addViolationAt从2.5弃用,但在3.0之前不会被删除,因此它们仍然可以使用很长时间.
但是......取自UPGRADE FROM 2.x到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();
));
Run Code Online (Sandbox Code Playgroud)
稍微从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());
Run Code Online (Sandbox Code Playgroud)