Skip to content

Commit

Permalink
feature #51348 [FrameworkBundle][Validator] Allow implementing valida…
Browse files Browse the repository at this point in the history
…tion groups provider outside DTOs (Yonel Ceruto)

This PR was squashed before being merged into the 6.4 branch.

Discussion
----------

[FrameworkBundle][Validator] Allow implementing validation groups provider outside DTOs

| Q             | A
| ------------- | ---
| Branch?       | 6.4
| Bug fix?      | no
| New feature?  | yes
| Deprecations? | no
| Tickets       | -
| License       | MIT
| Doc PR        | symfony/symfony-docs#18744

Alternative to #51233
Inspiration: #51012

Currently, you can determine the sequence of groups to apply dynamically based on the state of your DTO by implementing the `GroupSequenceProviderInterface` in your DTO class. https://symfony.com/doc/current/validation/sequence_provider.html#group-sequence-providers
```php
use Symfony\Component\Validator\GroupSequenceProviderInterface;

#[Assert\GroupSequenceProvider]
class UserDto implements GroupSequenceProviderInterface
{
    // ...

    public function getGroupSequence(): array|GroupSequence
    {
        if ($this->isCompanyType()) {
            return ['User', 'Company'];
        }

        return ['User'];
    }
}
```
It covers most of the common scenarios, but for more advanced ones, it may not be sufficient. Suppose now you need to provide the sequence of groups from an external configuration (or service) which can change its value dynamically:
```php
#[Assert\GroupSequenceProvider]
class UserDto implements GroupSequenceProviderInterface
{
    // ...

    public __constructor(private readonly ConfigService $config)
    {
    }

    public function getGroupSequence(): array|GroupSequence
    {
        if ($this->config->isEnabled()) {
            return ['User', $this->config->getGroup()];
        }

        return ['User'];
    }
}
```
This issue cannot be resolved at present without managing the DTO initialization and manually setting its dependencies. On the other hand, since the state of the DTO is not used at all, the implementation of the `GroupSequenceProviderInterface` becomes less fitting to the DTO responsibility. Further, stricter programming may raise a complaint about a violation of SOLID principles here.

So, the proposal of this PR is to allow configuring the validation groups provider outside of the DTO, while simultaneously enabling the registration of this provider as a service if necessary.

To achieve this, you'll need to implement a new `GroupProviderInterface` in a separate class, and configure it using the new `provider` option within the `GroupSequenceProvider` attribute:
```php
#[Assert\GroupSequenceProvider(provider: UserGroupProvider::class)]
class UserDto
{
    // ...
}

class UserGroupProvider implements GroupProviderInterface
{
    public __constructor(private readonly ConfigService $config)
    {
    }

    public function getGroups(object $object): array|GroupSequence
    {
        if ($this->config->isEnabled()) {
            return ['User', $this->config->getGroup()];
        }

        return ['User'];
    }
}
```
That's all you'll need to do if autowiring is enabled under your custom provider. Otherwise, you can manually tag your service with `validator.group_provider` to collect it and utilize it as a provider service during the validation process.

In conclusion, no more messing with the DTO structure, just use the new `class` option for more advanced use cases.

---

TODO:

- [x] Add tests
- [x] Create doc PR

Commits
-------

a3a089a [FrameworkBundle][Validator] Allow implementing validation groups provider outside DTOs
  • Loading branch information
fabpot committed Oct 20, 2023
2 parents a19c534 + a3a089a commit 0e201d1
Show file tree
Hide file tree
Showing 24 changed files with 316 additions and 72 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ class UnusedTagsPass implements CompilerPassInterface
'twig.runtime',
'validator.auto_mapper',
'validator.constraint_validator',
'validator.group_provider',
'validator.initializer',
'workflow',
];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@
use Symfony\Component\Uid\UuidV4;
use Symfony\Component\Validator\Constraints\ExpressionLanguageProvider;
use Symfony\Component\Validator\ConstraintValidatorInterface;
use Symfony\Component\Validator\GroupProviderInterface;
use Symfony\Component\Validator\Mapping\Loader\PropertyInfoLoader;
use Symfony\Component\Validator\ObjectInitializerInterface;
use Symfony\Component\Validator\Validation;
Expand Down Expand Up @@ -657,6 +658,8 @@ public function load(array $configs, ContainerBuilder $container)
->addTag('serializer.normalizer');
$container->registerForAutoconfiguration(ConstraintValidatorInterface::class)
->addTag('validator.constraint_validator');
$container->registerForAutoconfiguration(GroupProviderInterface::class)
->addTag('validator.group_provider');
$container->registerForAutoconfiguration(ObjectInitializerInterface::class)
->addTag('validator.initializer');
$container->registerForAutoconfiguration(MessageHandlerInterface::class)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@
->call('setConstraintValidatorFactory', [
service('validator.validator_factory'),
])
->call('setGroupProviderLocator', [
tagged_locator('validator.group_provider'),
])
->call('setTranslator', [
service('translator')->ignoreOnInvalid(),
])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1230,16 +1230,18 @@ public function testValidation()

$annotations = !class_exists(FullStack::class);

$this->assertCount($annotations ? 7 : 6, $calls);
$this->assertCount($annotations ? 8 : 7, $calls);
$this->assertSame('setConstraintValidatorFactory', $calls[0][0]);
$this->assertEquals([new Reference('validator.validator_factory')], $calls[0][1]);
$this->assertSame('setTranslator', $calls[1][0]);
$this->assertEquals([new Reference('translator', ContainerBuilder::IGNORE_ON_INVALID_REFERENCE)], $calls[1][1]);
$this->assertSame('setTranslationDomain', $calls[2][0]);
$this->assertSame(['%validator.translation_domain%'], $calls[2][1]);
$this->assertSame('addXmlMappings', $calls[3][0]);
$this->assertSame([$xmlMappings], $calls[3][1]);
$i = 3;
$this->assertSame('setGroupProviderLocator', $calls[1][0]);
$this->assertInstanceOf(ServiceLocatorArgument::class, $calls[1][1][0]);
$this->assertSame('setTranslator', $calls[2][0]);
$this->assertEquals([new Reference('translator', ContainerBuilder::IGNORE_ON_INVALID_REFERENCE)], $calls[2][1]);
$this->assertSame('setTranslationDomain', $calls[3][0]);
$this->assertSame(['%validator.translation_domain%'], $calls[3][1]);
$this->assertSame('addXmlMappings', $calls[4][0]);
$this->assertSame([$xmlMappings], $calls[4][1]);
$i = 4;
if ($annotations) {
$this->assertSame('enableAttributeMapping', $calls[++$i][0]);
}
Expand Down Expand Up @@ -1288,12 +1290,12 @@ public function testValidationAttributes()

$calls = $container->getDefinition('validator.builder')->getMethodCalls();

$this->assertCount(7, $calls);
$this->assertSame('enableAttributeMapping', $calls[4][0]);
$this->assertSame('addMethodMapping', $calls[5][0]);
$this->assertSame(['loadValidatorMetadata'], $calls[5][1]);
$this->assertSame('setMappingCache', $calls[6][0]);
$this->assertEquals([new Reference('validator.mapping.cache.adapter')], $calls[6][1]);
$this->assertCount(8, $calls);
$this->assertSame('enableAttributeMapping', $calls[5][0]);
$this->assertSame('addMethodMapping', $calls[6][0]);
$this->assertSame(['loadValidatorMetadata'], $calls[6][1]);
$this->assertSame('setMappingCache', $calls[7][0]);
$this->assertEquals([new Reference('validator.mapping.cache.adapter')], $calls[7][1]);
// no cache this time
}

Expand All @@ -1308,14 +1310,14 @@ public function testValidationLegacyAnnotations()

$calls = $container->getDefinition('validator.builder')->getMethodCalls();

$this->assertCount(8, $calls);
$this->assertSame('enableAttributeMapping', $calls[4][0]);
$this->assertCount(9, $calls);
$this->assertSame('enableAttributeMapping', $calls[5][0]);
if (method_exists(ValidatorBuilder::class, 'setDoctrineAnnotationReader')) {
$this->assertSame('setDoctrineAnnotationReader', $calls[5][0]);
$this->assertEquals([new Reference('annotation_reader')], $calls[5][1]);
$i = 6;
$this->assertSame('setDoctrineAnnotationReader', $calls[6][0]);
$this->assertEquals([new Reference('annotation_reader')], $calls[6][1]);
$i = 7;
} else {
$i = 5;
$i = 6;
}
$this->assertSame('addMethodMapping', $calls[$i][0]);
$this->assertSame(['loadValidatorMetadata'], $calls[$i][1]);
Expand All @@ -1335,16 +1337,16 @@ public function testValidationPaths()

$calls = $container->getDefinition('validator.builder')->getMethodCalls();

$this->assertCount(8, $calls);
$this->assertSame('addXmlMappings', $calls[3][0]);
$this->assertSame('addYamlMappings', $calls[4][0]);
$this->assertSame('enableAttributeMapping', $calls[5][0]);
$this->assertSame('addMethodMapping', $calls[6][0]);
$this->assertSame(['loadValidatorMetadata'], $calls[6][1]);
$this->assertSame('setMappingCache', $calls[7][0]);
$this->assertEquals([new Reference('validator.mapping.cache.adapter')], $calls[7][1]);
$this->assertCount(9, $calls);
$this->assertSame('addXmlMappings', $calls[4][0]);
$this->assertSame('addYamlMappings', $calls[5][0]);
$this->assertSame('enableAttributeMapping', $calls[6][0]);
$this->assertSame('addMethodMapping', $calls[7][0]);
$this->assertSame(['loadValidatorMetadata'], $calls[7][1]);
$this->assertSame('setMappingCache', $calls[8][0]);
$this->assertEquals([new Reference('validator.mapping.cache.adapter')], $calls[8][1]);

$xmlMappings = $calls[3][1][0];
$xmlMappings = $calls[4][1][0];
$this->assertCount(3, $xmlMappings);
try {
// Testing symfony/symfony
Expand All @@ -1355,7 +1357,7 @@ public function testValidationPaths()
}
$this->assertStringEndsWith('TestBundle/Resources/config/validation.xml', $xmlMappings[1]);

$yamlMappings = $calls[4][1][0];
$yamlMappings = $calls[5][1][0];
$this->assertCount(1, $yamlMappings);
$this->assertStringEndsWith('TestBundle/Resources/config/validation.yml', $yamlMappings[0]);
}
Expand All @@ -1370,7 +1372,7 @@ public function testValidationPathsUsingCustomBundlePath()
]);

$calls = $container->getDefinition('validator.builder')->getMethodCalls();
$xmlMappings = $calls[3][1][0];
$xmlMappings = $calls[4][1][0];
$this->assertCount(3, $xmlMappings);

try {
Expand All @@ -1382,7 +1384,7 @@ public function testValidationPathsUsingCustomBundlePath()
}
$this->assertStringEndsWith('CustomPathBundle/Resources/config/validation.xml', $xmlMappings[1]);

$yamlMappings = $calls[4][1][0];
$yamlMappings = $calls[5][1][0];
$this->assertCount(1, $yamlMappings);
$this->assertStringEndsWith('CustomPathBundle/Resources/config/validation.yml', $yamlMappings[0]);
}
Expand All @@ -1395,9 +1397,9 @@ public function testValidationNoStaticMethod()

$annotations = !class_exists(FullStack::class);

$this->assertCount($annotations ? 6 : 5, $calls);
$this->assertSame('addXmlMappings', $calls[3][0]);
$i = 3;
$this->assertCount($annotations ? 7 : 6, $calls);
$this->assertSame('addXmlMappings', $calls[4][0]);
$i = 4;
if ($annotations) {
$this->assertSame('enableAttributeMapping', $calls[++$i][0]);
}
Expand Down Expand Up @@ -1426,14 +1428,14 @@ public function testValidationMapping()

$calls = $container->getDefinition('validator.builder')->getMethodCalls();

$this->assertSame('addXmlMappings', $calls[3][0]);
$this->assertCount(3, $calls[3][1][0]);

$this->assertSame('addYamlMappings', $calls[4][0]);
$this->assertSame('addXmlMappings', $calls[4][0]);
$this->assertCount(3, $calls[4][1][0]);
$this->assertStringContainsString('foo.yml', $calls[4][1][0][0]);
$this->assertStringContainsString('validation.yml', $calls[4][1][0][1]);
$this->assertStringContainsString('validation.yaml', $calls[4][1][0][2]);

$this->assertSame('addYamlMappings', $calls[5][0]);
$this->assertCount(3, $calls[5][1][0]);
$this->assertStringContainsString('foo.yml', $calls[5][1][0][0]);
$this->assertStringContainsString('validation.yml', $calls[5][1][0][1]);
$this->assertStringContainsString('validation.yaml', $calls[5][1][0][2]);
}

public function testValidationAutoMapping()
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Component/Validator/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ CHANGELOG
* Deprecate `ValidatorBuilder::enableAnnotationMapping()`, use `ValidatorBuilder::enableAttributeMapping()` instead
* Deprecate `ValidatorBuilder::disableAnnotationMapping()`, use `ValidatorBuilder::disableAttributeMapping()` instead
* Deprecate `AnnotationLoader`, use `AttributeLoader` instead
* Add `GroupProviderInterface` to implement validation group providers outside the underlying class

6.3
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,25 @@

namespace Symfony\Component\Validator\Constraints;

use Doctrine\Common\Annotations\Annotation\NamedArgumentConstructor;
use Symfony\Component\Validator\Attribute\HasNamedArguments;

/**
* Attribute to define a group sequence provider.
*
* @Annotation
*
* @NamedArgumentConstructor
*
* @Target({"CLASS", "ANNOTATION"})
*
* @author Bernhard Schussek <bschussek@gmail.com>
*/
#[\Attribute(\Attribute::TARGET_CLASS)]
class GroupSequenceProvider
{
#[HasNamedArguments]
public function __construct(public ?string $provider = null)
{
}
}
30 changes: 30 additions & 0 deletions src/Symfony/Component/Validator/GroupProviderInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Component\Validator;

use Symfony\Component\Validator\Constraints\GroupSequence;

/**
* Defines the interface for a validation group provider.
*
* @author Yonel Ceruto <yonelceruto@gmail.com>
*/
interface GroupProviderInterface
{
/**
* Returns which validation groups should be used for a certain state
* of the object.
*
* @return string[]|string[][]|GroupSequence
*/
public function getGroups(object $object): array|GroupSequence;
}
21 changes: 20 additions & 1 deletion src/Symfony/Component/Validator/Mapping/ClassMetadata.php
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,13 @@ class ClassMetadata extends GenericMetadata implements ClassMetadataInterface
*/
public bool $groupSequenceProvider = false;

/**
* @internal This property is public in order to reduce the size of the
* class' serialized representation. Do not access it. Use
* {@link getGroupProvider()} instead.
*/
public ?string $groupProvider = null;

/**
* The strategy for traversing traversable objects.
*
Expand Down Expand Up @@ -123,6 +130,7 @@ public function __sleep(): array
'getters',
'groupSequence',
'groupSequenceProvider',
'groupProvider',
'members',
'name',
'properties',
Expand Down Expand Up @@ -319,6 +327,7 @@ public function addGetterMethodConstraints(string $property, string $method, arr
public function mergeConstraints(self $source)
{
if ($source->isGroupSequenceProvider()) {
$this->setGroupProvider($source->getGroupProvider());
$this->setGroupSequenceProvider(true);
}

Expand Down Expand Up @@ -432,7 +441,7 @@ public function setGroupSequenceProvider(bool $active)
throw new GroupDefinitionException('Defining a group sequence provider is not allowed with a static group sequence.');
}

if (!$this->getReflectionClass()->implementsInterface(GroupSequenceProviderInterface::class)) {
if (null === $this->groupProvider && !$this->getReflectionClass()->implementsInterface(GroupSequenceProviderInterface::class)) {
throw new GroupDefinitionException(sprintf('Class "%s" must implement GroupSequenceProviderInterface.', $this->name));
}

Expand All @@ -444,6 +453,16 @@ public function isGroupSequenceProvider(): bool
return $this->groupSequenceProvider;
}

public function setGroupProvider(?string $provider): void
{
$this->groupProvider = $provider;
}

public function getGroupProvider(): ?string
{
return $this->groupProvider;
}

public function getCascadingStrategy(): int
{
return $this->cascadingStrategy;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
* @see GroupSequence
* @see GroupSequenceProviderInterface
* @see TraversalStrategy
*
* @method string|null getGroupProvider()
*/
interface ClassMetadataInterface extends MetadataInterface
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ public function loadClassMetadata(ClassMetadata $metadata): bool
if ($constraint instanceof GroupSequence) {
$metadata->setGroupSequence($constraint->groups);
} elseif ($constraint instanceof GroupSequenceProvider) {
$metadata->setGroupProvider($constraint->provider);
$metadata->setGroupSequenceProvider(true);
} elseif ($constraint instanceof Constraint) {
$metadata->addConstraint($constraint);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,7 @@ private function loadClassesFromXml(): void
private function loadClassMetadataFromXml(ClassMetadata $metadata, \SimpleXMLElement $classDescription): void
{
if (\count($classDescription->{'group-sequence-provider'}) > 0) {
$metadata->setGroupProvider($classDescription->{'group-sequence-provider'}[0]->value ?: null);
$metadata->setGroupSequenceProvider(true);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,9 @@ private function loadClassesFromYaml(): void
private function loadClassMetadataFromYaml(ClassMetadata $metadata, array $classDescription): void
{
if (isset($classDescription['group_sequence_provider'])) {
if (\is_string($classDescription['group_sequence_provider'])) {
$metadata->setGroupProvider($classDescription['group_sequence_provider']);
}
$metadata->setGroupSequenceProvider(
(bool) $classDescription['group_sequence_provider']
);
Expand Down

0 comments on commit 0e201d1

Please sign in to comment.