@@ -23,27 +23,66 @@ Basic Usage
2323Suppose that you have different places where a user password must be validated,
2424you can create your own named set or requirements to be reused consistently everywhere::
2525
26- // src/Validator/Constraints/PasswordRequirements.php
27- namespace App\Validator\Constraints;
28-
29- use Symfony\Component\Validator\Constraints\Compound;
30- use Symfony\Component\Validator\Constraints as Assert;
31-
32- /**
33- * @Annotation
34- */
35- class PasswordRequirements extends Compound
36- {
37- protected function getConstraints(array $options): array
26+ .. configuration-block ::
27+
28+ .. code-block :: php-annotations
29+
30+ // src/Validator/Constraints/PasswordRequirements.php
31+ namespace App\Validator\Constraints;
32+
33+ use Symfony\Component\Validator\Constraints\Compound;
34+ use Symfony\Component\Validator\Constraints as Assert;
35+
36+ /**
37+ * @Annotation
38+ */
39+ class PasswordRequirements extends Compound
3840 {
39- return [
40- new Assert\NotBlank(),
41- new Assert\Type('string'),
42- new Assert\Length(['min' => 12]),
43- new Assert\NotCompromisedPassword(),
44- ];
41+ protected function getConstraints(array $options): array
42+ {
43+ return [
44+ new Assert\NotBlank(),
45+ new Assert\Type('string'),
46+ new Assert\Length(['min' => 12]),
47+ new Assert\NotCompromisedPassword(),
48+ ];
49+ }
4550 }
46- }
51+
52+ .. code-block :: php-attributes
53+
54+ // src/Validator/Constraints/PasswordRequirements.php
55+ namespace App\Validator\Constraints;
56+
57+ use Symfony\Component\Validator\Constraints\Compound;
58+ use Symfony\Component\Validator\Constraints as Assert;
59+
60+ #[\Attribute]
61+ class PasswordRequirements extends Compound
62+ {
63+ protected function getConstraints(array $options): array
64+ {
65+ return [
66+ new Assert\NotBlank(),
67+ new Assert\Type('string'),
68+ new Assert\Length(['min' => 12]),
69+ new Assert\NotCompromisedPassword(),
70+ ];
71+ }
72+ }
73+
74+ .. versionadded :: 5.2
75+
76+ The ability to use PHP attributes to configure constraints was introduced in
77+ Symfony 5.2. Prior to this, Doctrine Annotations were the only way to
78+ annotate constraints.
79+
80+ .. note ::
81+
82+ The ``@Annotation `` or ``#[\Attribute] `` annotation is necessary for this new constraint in
83+ order to make it available for use in classes via annotations.
84+ Options for your constraint are represented as public properties on the
85+ constraint class.
4786
4887You can now use it anywhere you need it:
4988
@@ -64,6 +103,19 @@ You can now use it anywhere you need it:
64103 public $password;
65104 }
66105
106+ .. code-block :: php-attributes
107+
108+ // src/User/RegisterUser.php
109+ namespace App\User;
110+
111+ use App\Validator\Constraints as AcmeAssert;
112+
113+ class RegisterUser
114+ {
115+ #[AcmeAssert\PasswordRequirements]
116+ public $password;
117+ }
118+
67119 .. code-block :: yaml
68120
69121 # config/validator/validation.yaml
0 commit comments