Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Validator] Allow to define a reusable set of constraints #34334

Open
wants to merge 3 commits into
base: master
from

Conversation

@ogizanagi
Copy link
Member

ogizanagi commented Nov 12, 2019

Q A
Branch? 5.1
Bug fix? no
New feature? yes
Deprecations? no
Tickets N/A
License MIT
Doc PR TODO

The goal of this feature is to simplify writing a set of validation constraints to be reused consistently across the application. Which is especially useful with DTOs, as a same set of constraints can be used in different places.

For instance, given multiple DTOs containing the new user password in for different use-cases (register, forgot pwd, change pwd), the same rules apply on the property. Hence with this PR, you can write a single constraint class to be reused:

/**
 * @Annotation
 */
class MatchesPasswordRequirements extends Compound
{
    protected function getConstraints(array $options): array
    {
        return [
            new NotBlank(),
            new Type('string'),
            new Length(['min' => 12]),
            new NotCompromisedPassword(),
        ];
    }
}

I'm open to better naming and ways to expose the options to the Compound::getConstraints method, so options can be forwarded to the nested constraints for most specific use-cases.

@ogizanagi ogizanagi added this to the next milestone Nov 12, 2019
@ogizanagi ogizanagi force-pushed the ogizanagi:validator_compound_constraint branch from c32f414 to 2bae271 Nov 12, 2019
return CompoundValidator::class;
}
abstract protected function getConstraints(array $options): array;

This comment has been minimized.

Copy link
@ogizanagi

ogizanagi Nov 12, 2019

Author Member

Instead of exposing the normalized options as a method argument, we could rely on populated instance properties by calling the Constraint::__construct beforehand (as in original commit 9fab172#diff-fa2f43b5bc196bf979f6e59ec699e462R33-R41). But this would call this construct twice as it'll be called in parent one too. This can either be workaround to ensure this constructor is called once, or solved in a totally different fashion (don't extend Composite but used a shared trait?)

@ogizanagi ogizanagi force-pushed the ogizanagi:validator_compound_constraint branch from 2bae271 to 44ba17e Nov 21, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
2 participants
You can’t perform that action at this time.