简体   繁体   English

如何创建一个“ OR” Symfony验证器约束

[英]How to create an “OR” Symfony Validator Constraint

How would one go about creating a Symfony 4.2 constraint that validates multiple batches of constraints, but fails only if all of them fail? 如何创建一个Symfony 4.2约束来验证多批约束,但是只有所有约束都失败时才会失败?

Here's my use case. 这是我的用例。

I want to validate a variable that can be either an object of specific class, or an array representing an object of the same class. 我想验证一个变量,该变量可以是特定类的对象,也可以是表示同一类对象的数组。 I would then have 2 cases: 然后,我将有两种情况:

  1. I would want to validate against Type(type=array) constraint and then a Collection(fields={...}) constraint to ensure this is an array with proper structure that I can then deserialize and get the object; 我想先验证Type(type=array)约束,然后再验证Collection(fields={...})约束,以确保这是一个具有适当结构的数组,然后我可以反序列化并获取对象;
  2. or I would want to validate against Type(type=MyClassName) . 或者我想针对Type(type=MyClassName)进行验证。

So, the final constraint should succeed if either case 1 or case 2 succeeds, and should fail only if both fail (say a string is passed). 因此,如果情况1或情况2成功,则最终约束应该成功,并且只有当两个都失败(例如,传递了string )时,最终约束才应该失败。

I feel groups could be useful somehow, but I am not entirely sure how exactly to use them in this case. 我认为小组可能会以某种方式有用,但我不确定在这种情况下如何正确使用小组。


I already have an idea how to implement this, but somehow it fails and I can't figure out why: 我已经有了实现该方法的想法,但是以某种方式失败了,我不知道为什么:

$violations1 = $this->context->getValidator()->validate($value, $constraints1);
$violations2 = $this->context->getValidator()->validate($value, $constraints2);

// Check both violations and if at least one of them is empty - succeed.
// If all of them fail, copy violations to the current context.

As you can see I would validate the value against $constraints1 which is an array of constraints to check if the value is a valid array. 如您所见,我将针对$constraints1验证该值, $constraints1是一个约束数组,以检查该值是否为有效数组。 Then I would validate the value against $constraints2 which is a different array of constraints that checks if the value is an object of specific class. 然后,我将针对$constraints2验证该值,后者是一个不同的约束数组,用于检查该值是否是特定类的对象。

At this point I want to just copy the violations and fail, or succeed if either $violations1 or $violations2 are empty. 在这一点上,我只想复制冲突并失败,或者如果$violations1$violations2为空,则成功。

The problem is, that for some reason $violations2 is always empty, even if it should fail. 问题是,由于某种原因, $violations2 始终为空,即使它应该失败。 As if the validator refuses to validate the same value twice, even if it's against a different set of constraints. 好像验证器拒绝两次验证相同的值,即使它受到一组不同的约束。 Is this true and how to circumvent it? 这是真的吗?如何规避呢?

You can use the expression constraint . 您可以使用表达式约束 It allows to combine multiple tests with 'or'. 它允许将多个测试与“或”组合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM