Quantcast
Channel: Symfony Blog
Viewing all articles
Browse latest Browse all 3059

New in Symfony 5.1: Reusable sets of constraints

$
0
0
Maxime Steinhausser

Contributed by
Maxime Steinhausser
in #34334.

In certain applications is common to reuse the same set of constraints in multiple places. Consider for example an application that allows to register users, change passwords, remember forgotten passwords, etc. That application may use differentDTOs for each feature but all of them contain the new user password, which must be validated in the same way in all cases.

In Symfony 5.1, you can quickly create a validator reusing other constraints, no matter if they are built-in or custom made, thanks to the new Compound constraint:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
namespaceApp\Validator;useSymfony\Component\Validator\Constraints\Compound;useSymfony\Component\Validator\Constraints\Length;useSymfony\Component\Validator\Constraints\NotBlank;useSymfony\Component\Validator\Constraints\NotCompromisedPassword;useSymfony\Component\Validator\Constraints\Type;/** * @Annotation */classMatchesPasswordRequirementsextendsCompound{protectedfunctiongetConstraints(array$options):array{return[newNotBlank(),newType('string'),newLength(['min'=>12]),newNotCompromisedPassword(),];}}

Now you can apply this constraint to your objects as usual:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
namespaceApp\Dto;// ...useApp\Validator\MatchesPasswordRequirements;classChangePasswordDto{/**     * @MatchesPasswordRequirements     */private$newPassword;// ...}

Validate constraints sequentially

Maxime Steinhausser

Contributed by
Maxime Steinhausser
in #34456.

In Symfony 5.1 we also added a different, but related, feature to validate a set of constraints sequentially. This was already possible thanks to the GroupSequence constraint, but in Symfony 5.1 we simplified this feature with the introduction of a new Sequentially constraint.

The argument of the Sequentially constraint is a set of one or more constraints. Symfony will apply them in that same order and if any of them fails, it will stop and the rest of constraints won't be tested. This is useful to prevent both unexpected type exceptions thrown by some constraints and unnecessary calls to slow constraints:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
/** * @var string * * @Assert\Sequentially({ *     @Assert\Type("string"), *     @Assert\Length(min="4"), *     @Assert\Regex("[a-z]"), *     @SomeCustomConstraintWithHeavyExternalCalls(), * }) */public$someProperty;

Be trained by Symfony experts - 2020-03-16 Lille - 2020-03-16 Lyon - 2020-03-16 Lyon

Viewing all articles
Browse latest Browse all 3059

Trending Articles