Commit f9abefa
committed
feature #61545 [Validator] Add
This PR was merged into the 7.4 branch.
Discussion
----------
[Validator] Add `#[ExtendsValidationFor]` to declare new constraints for a class
| Q | A
| ------------- | ---
| Branch? | 7.4
| Bug fix? | no
| New feature? | yes
| Deprecations? | no
| Issues | -
| License | MIT
This PR builds on #61528
I propose to add a `#[ExtendsValidationFor]` attribute that allows adding validation constraints to another class.
This is typically needed for third party classes. For context, Sylius has a nice doc about this:
https://docs.sylius.com/the-customization-guide/customizing-validation
At the moment, the only way to achieve this is by declaring the new constraints in the (hardcoded) `config/validation/` folder, using either xml or yaml. No attributes.
With this PR, one will be able to define those extra constraints using PHP attributes, set on classes that'd mirror the properties/getters of the targeted class. The compiler pass will ensure that all properties/getters declared in these source classes also exist in the target class. (source = the app's class that declares the new constraints; target = the existing class to add constraints to.)
```php
#[ExtendsValidationFor(TargetClass::class)]
abstract class SourceClass
{
#[Assert\NotBlank(groups: ['my_app'])]
#[Assert\Length(min: 3, groups: ['my_app'])]
public string $name = '';
#[Assert\Email(groups: ['my_app'])]
public string $email = '';
#[Assert\Range(min: 18, groups: ['my_app'])]
public int $age = 0;
}
```
(I made the class abstract because it's not supposed to be instantiated - but it's not mandatory.)
Here are the basics of how this works:
1. During container compilation, classes marked with `#[ExtendsValidationFor(Target::class)]` are collected and validated: the container checks that members declared on the source exist on the target. If not, a `MappingException` is thrown.
2. The validator is configured to map the target to its source classes.
3. At runtime, when loading validation metadata for the target, attributes (constraints, callbacks, group providers) are read from both the target and its mapped source classes and applied accordingly.
Commits
-------
e884a769a70 [Validator] Add `#[ExtendsValidationFor]` to declare new constraints for a class#[ExtendsValidationFor] to declare new constraints for a class (nicolas-grekas)1 file changed
+8
-1
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
216 | 216 | | |
217 | 217 | | |
218 | 218 | | |
| 219 | + | |
219 | 220 | | |
220 | 221 | | |
221 | 222 | | |
| |||
1821 | 1822 | | |
1822 | 1823 | | |
1823 | 1824 | | |
1824 | | - | |
| 1825 | + | |
| 1826 | + | |
1825 | 1827 | | |
1826 | 1828 | | |
1827 | 1829 | | |
| 1830 | + | |
| 1831 | + | |
| 1832 | + | |
| 1833 | + | |
| 1834 | + | |
1828 | 1835 | | |
1829 | 1836 | | |
1830 | 1837 | | |
| |||
0 commit comments