目前我遇到一个Symfony验证器可选约束的问题。
如果该字段已经通过(键在ParameterBag中),我需要parentId规则只处理它,但不幸的是,Symfony总是尝试验证,即使它没有传递。
public function validateParameters(ParameterBag $request, Collection $validatorRules)
{
$validatorErrors = $this->validator->validateValue($request->all(), $validatorRules);
if (count($validatorErrors) !== 0) {
throw new \Exception($validatorErrors[0]->getPropertyPath() . ' - ' . $validatorErrors[0]->getMessage());
}
echo 'yay!';
exit;
}
public function create(Application $app, Request $request)
{
// check that the validation rules pass for this service
$this->validateParameters($request->request, new Collection([
'parentId' => [new Assert\Optional(), new Assert\Regex(['pattern' => '/^[0-9]\d*$/'])],
'title' => [new Assert\NotBlank(), new Assert\Length(['min' => 3])],
'description' => [new Assert\NotBlank()],
]));
// ...............
}
任何帮助或指针都将不胜感激,因为Symfony文档主要讨论直接针对对象进行验证,但我想针对传入的ParameterBag进行验证。