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

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

Merged
merged 1 commit into from
Oct 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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