For context, i'm currently working on a vanilla PHP project, no framework, mostly no POO, all of it not my choice, i'm just the duct tape guy. So, for any response involving code examples, please consider the component to be used as standalone and only illustrate with plain PHP examples, no annotations, attributes, YAML, XML or anything like that.
I've started using symfony's Validator component (version 5.3) to sanitize user input. After reading the doc of Validation component and searching about something like that about everywhere, I cannot find example of how to combine Constraints in the following way :
Consider 3 constraints, A, B, C.
I would like to apply thoses constraints to a field so it is valid if A || (B && C). I can easily make A && B && C, i know how to use constraint AtLeastOneOf to do A || B || C or even A && (B || C), but i cannot figure A || (B && C), for that i would need a way to group the constraint B and C inside my AtLeastOneOf constraint.
So, here is an example of my problem (note that thoses constraints are just for example, the important part is the A || (B && C) problem, i know there is a solution without using A || (B && C) for this particular case, it's not what i'm looking for) :
<?php
use Symfony\Component\Validator\Constraints\Length;
use Symfony\Component\Validator\Constraints\EqualTo;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Validation;
$var = 'Something';
// How i would have done it in plain PHP
if ($var == '' || ($var != '' && mb_strlen($var) < 10)) {
echo '$var must be empty string or less than 10 chars';
}
// How to do it with validator
$validator = Validation::createValidator();
$violations = $validator->validate($var, [
// How to do it whith constraints ?
]);
if (count($violations)) {
echo 'First error : ' . $violations[0]->getMessage();
}
As it's the first time that i use symfony Validation (i may have used it years ago in a Silex project, but time have past), i guess there must be a solution that i'm simply not aware of.
To be clear, i have find and read How to create an "OR" Symfony Validator Constraint, i know i could use a Custom constraint, a Callback constraint or an Expression constraint to do this, but this is not what i'm looking for. I'm looking for something more straightforward, my point being : if i can do it easily with boolean operators and parentheses, then i should be able to do it as easily with validations constraints !
If there is no way to do that, then fine, i will use callback or something like that and afterward proceed to look if i can create some kind of a solution and hopefully submit it to symfony. But if there is a way, i would really like to know !