@@ -502,6 +502,9 @@ A class constraint validator must be applied to the class itself:
502
502
Testing Custom Constraints
503
503
--------------------------
504
504
505
+ Atomic Constraints
506
+ ~~~~~~~~~~~~~~~~~~
507
+
505
508
Use the :class: `Symfony\\ Component\\ Validator\\ Test\\ ConstraintValidatorTestCase `
506
509
class to simplify writing unit tests for your custom constraints::
507
510
@@ -545,3 +548,70 @@ class to simplify writing unit tests for your custom constraints::
545
548
// ...
546
549
}
547
550
}
551
+
552
+ Compound Constraints
553
+ ~~~~~~~~~~~~~~~~~~~~
554
+
555
+ Let's say you create a compound constraint that checks if a string meets
556
+ your minimum requirements for your password policy::
557
+
558
+ // src/Validator/MatchPasswordPolicy.php
559
+ namespace App\Validator;
560
+
561
+ use Symfony\Component\Validator\Constraints as Assert;
562
+
563
+ #[\Attribute]
564
+ class MatchPasswordPolicy extends Assert\Compound
565
+ {
566
+ protected function getConstraints(array $options): array
567
+ {
568
+ return [
569
+ new Assert\NotBlank(allowNull: false),
570
+ new Assert\Length(min: 8, max: 255),
571
+ new Assert\NotCompromisedPassword(),
572
+ new Assert\Type('string'),
573
+ new Assert\Regex('/[A-Z]+/'),
574
+ ];
575
+ }
576
+ }
577
+
578
+ You can use the :class: `Symfony\\ Component\\ Validator\\ Test\\ CompoundConstraintTestCase `
579
+ class to check precisely which of the constraints failed to pass::
580
+
581
+ // tests/Validator/MatchPasswordPolicyTest.php
582
+ namespace App\Tests\Validator;
583
+
584
+ use Symfony\Component\Validator\Constraints as Assert;
585
+ use Symfony\Component\Validator\Test\CompoundConstraintTestCase;
586
+
587
+ class MatchPasswordPolicyTest extends CompoundConstraintTestCase
588
+ {
589
+ public function createCompound(): Assert\Compound
590
+ {
591
+ return new MatchPasswordPolicy();
592
+ }
593
+
594
+ public function testInvalidPassword(): void
595
+ {
596
+ $this->validateValue('azerty123');
597
+
598
+ // check all constraints pass except for the
599
+ // password leak and the uppercase letter checks
600
+ $this->assertViolationsRaisedByCompound([
601
+ new Assert\NotCompromisedPassword(),
602
+ new Assert\Regex('/[A-Z]+/'),
603
+ ]);
604
+ }
605
+
606
+ public function testValid(): void
607
+ {
608
+ $this->validateValue('VERYSTR0NGP4$$WORD#%!');
609
+
610
+ $this->assertNoViolation();
611
+ }
612
+ }
613
+
614
+ .. versionadded :: 7.2
615
+
616
+ The :class: `Symfony\\ Component\\ Validator\\ Test\\ CompoundConstraintTestCase `
617
+ class was introduced in Symfony 7.2.
0 commit comments