[Validation][FrameworkBundle] Allow EnableAutoMapping to work without auto-mapping namespaces

This commit is contained in:
Maxime Steinhausser 2019-11-29 10:39:08 +01:00
parent 4e44baf1bb
commit 00b46fa72e
10 changed files with 21 additions and 30 deletions

View File

@ -164,8 +164,8 @@ Lock
* Deprecated `Symfony\Component\Lock\StoreInterface` in favor of `Symfony\Component\Lock\BlockingStoreInterface` and * Deprecated `Symfony\Component\Lock\StoreInterface` in favor of `Symfony\Component\Lock\BlockingStoreInterface` and
`Symfony\Component\Lock\PersistingStoreInterface`. `Symfony\Component\Lock\PersistingStoreInterface`.
* `Factory` is deprecated, use `LockFactory` instead * `Factory` is deprecated, use `LockFactory` instead
* Deprecated services `lock.store.flock`, `lock.store.semaphore`, `lock.store.memcached.abstract` and `lock.store.redis.abstract`, * Deprecated services `lock.store.flock`, `lock.store.semaphore`, `lock.store.memcached.abstract` and `lock.store.redis.abstract`,
use `StoreFactory::createStore` instead. use `StoreFactory::createStore` instead.
Mailer Mailer
------ ------
@ -360,6 +360,7 @@ TwigBundle
Validator Validator
--------- ---------
* [BC BREAK] Using null as `$classValidatorRegexp` value in `DoctrineLoader::__construct` or `PropertyInfoLoader::__construct` will not enable auto-mapping for all classes anymore, use `'{.*}'` instead.
* Deprecated passing an `ExpressionLanguage` instance as the second argument of `ExpressionValidator::__construct()`. * Deprecated passing an `ExpressionLanguage` instance as the second argument of `ExpressionValidator::__construct()`.
* Deprecated using anything else than a `string` as the code of a `ConstraintViolation`, a `string` type-hint will * Deprecated using anything else than a `string` as the code of a `ConstraintViolation`, a `string` type-hint will
be added to the constructor of the `ConstraintViolation` class and to the `ConstraintViolationBuilder::setCode()` be added to the constructor of the `ConstraintViolation` class and to the `ConstraintViolationBuilder::setCode()`

View File

@ -4,6 +4,7 @@ CHANGELOG
4.4.0 4.4.0
----- -----
* [BC BREAK] using null as `$classValidatorRegexp` value in `DoctrineLoader::__construct` will not enable auto-mapping for all classes anymore, use `'{.*}'` instead.
* added `DoctrineClearEntityManagerWorkerSubscriber` * added `DoctrineClearEntityManagerWorkerSubscriber`
* deprecated `RegistryInterface`, use `Doctrine\Persistence\ManagerRegistry` * deprecated `RegistryInterface`, use `Doctrine\Persistence\ManagerRegistry`
* added support for invokable event listeners * added support for invokable event listeners

View File

@ -30,7 +30,6 @@ use Symfony\Component\Validator\Mapping\PropertyMetadata;
use Symfony\Component\Validator\Mapping\TraversalStrategy; use Symfony\Component\Validator\Mapping\TraversalStrategy;
use Symfony\Component\Validator\Tests\Fixtures\Entity; use Symfony\Component\Validator\Tests\Fixtures\Entity;
use Symfony\Component\Validator\Validation; use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\ValidatorBuilder;
/** /**
* @author Kévin Dunglas <dunglas@gmail.com> * @author Kévin Dunglas <dunglas@gmail.com>
@ -152,10 +151,6 @@ class DoctrineLoaderTest extends TestCase
public function testFieldMappingsConfiguration() public function testFieldMappingsConfiguration()
{ {
if (!method_exists(ValidatorBuilder::class, 'addLoader')) {
$this->markTestSkipped('Auto-mapping requires symfony/validation 4.2+');
}
$validator = Validation::createValidatorBuilder() $validator = Validation::createValidatorBuilder()
->addMethodMapping('loadValidatorMetadata') ->addMethodMapping('loadValidatorMetadata')
->enableAnnotationMapping() ->enableAnnotationMapping()
@ -180,7 +175,7 @@ class DoctrineLoaderTest extends TestCase
*/ */
public function testClassValidator(bool $expected, string $classValidatorRegexp = null) public function testClassValidator(bool $expected, string $classValidatorRegexp = null)
{ {
$doctrineLoader = new DoctrineLoader(DoctrineTestHelper::createTestEntityManager(), $classValidatorRegexp); $doctrineLoader = new DoctrineLoader(DoctrineTestHelper::createTestEntityManager(), $classValidatorRegexp, false);
$classMetadata = new ClassMetadata(DoctrineLoaderEntity::class); $classMetadata = new ClassMetadata(DoctrineLoaderEntity::class);
$this->assertSame($expected, $doctrineLoader->loadClassMetadata($classMetadata)); $this->assertSame($expected, $doctrineLoader->loadClassMetadata($classMetadata));
@ -189,7 +184,8 @@ class DoctrineLoaderTest extends TestCase
public function regexpProvider() public function regexpProvider()
{ {
return [ return [
[true, null], [false, null],
[true, '{.*}'],
[true, '{^'.preg_quote(DoctrineLoaderEntity::class).'$|^'.preg_quote(Entity::class).'$}'], [true, '{^'.preg_quote(DoctrineLoaderEntity::class).'$|^'.preg_quote(Entity::class).'$}'],
[false, '{^'.preg_quote(Entity::class).'$}'], [false, '{^'.preg_quote(Entity::class).'$}'],
]; ];
@ -197,13 +193,9 @@ class DoctrineLoaderTest extends TestCase
public function testClassNoAutoMapping() public function testClassNoAutoMapping()
{ {
if (!method_exists(ValidatorBuilder::class, 'addLoader')) {
$this->markTestSkipped('Auto-mapping requires symfony/validation 4.2+');
}
$validator = Validation::createValidatorBuilder() $validator = Validation::createValidatorBuilder()
->enableAnnotationMapping() ->enableAnnotationMapping()
->addLoader(new DoctrineLoader(DoctrineTestHelper::createTestEntityManager())) ->addLoader(new DoctrineLoader(DoctrineTestHelper::createTestEntityManager(), '{.*}'))
->getValidator(); ->getValidator();
$classMetadata = $validator->getMetadataFor(new DoctrineLoaderNoAutoMappingEntity()); $classMetadata = $validator->getMetadataFor(new DoctrineLoaderNoAutoMappingEntity());

View File

@ -861,7 +861,7 @@ class Configuration implements ConfigurationInterface
->end() ->end()
->end() ->end()
->arrayNode('auto_mapping') ->arrayNode('auto_mapping')
->info('A collection of namespaces for which auto-mapping will be enabled.') ->info('A collection of namespaces for which auto-mapping will be enabled by default, or null to opt-in with the EnableAutoMapping constraint.')
->example([ ->example([
'App\\Entity\\' => [], 'App\\Entity\\' => [],
'App\\WithSpecificLoaders\\' => ['validator.property_info_loader'], 'App\\WithSpecificLoaders\\' => ['validator.property_info_loader'],

View File

@ -1312,7 +1312,7 @@ class FrameworkExtension extends Extension
} }
$container->setParameter('validator.auto_mapping', $config['auto_mapping']); $container->setParameter('validator.auto_mapping', $config['auto_mapping']);
if (!$propertyInfoEnabled || !$config['auto_mapping'] || !class_exists(PropertyInfoLoader::class)) { if (!$propertyInfoEnabled || !class_exists(PropertyInfoLoader::class)) {
$container->removeDefinition('validator.property_info_loader'); $container->removeDefinition('validator.property_info_loader');
} }

View File

@ -4,19 +4,20 @@ CHANGELOG
4.4.0 4.4.0
----- -----
* added `EnableAutoMapping` and `DisableAutoMapping` constraints to enable or disable auto mapping for class or a property * [BC BREAK] using null as `$classValidatorRegexp` value in `PropertyInfoLoader::__construct` will not enable auto-mapping for all classes anymore, use `'{.*}'` instead.
* added `EnableAutoMapping` and `DisableAutoMapping` constraints to enable or disable auto mapping for class or a property
* using anything else than a `string` as the code of a `ConstraintViolation` is deprecated, a `string` type-hint will * using anything else than a `string` as the code of a `ConstraintViolation` is deprecated, a `string` type-hint will
be added to the constructor of the `ConstraintViolation` class and to the `ConstraintViolationBuilder::setCode()` be added to the constructor of the `ConstraintViolation` class and to the `ConstraintViolationBuilder::setCode()`
method in 5.0 method in 5.0
* deprecated passing an `ExpressionLanguage` instance as the second argument of `ExpressionValidator::__construct()`. Pass it as the first argument instead. * deprecated passing an `ExpressionLanguage` instance as the second argument of `ExpressionValidator::__construct()`. Pass it as the first argument instead.
* added the `compared_value_path` parameter in violations when using any * added the `compared_value_path` parameter in violations when using any
comparison constraint with the `propertyPath` option. comparison constraint with the `propertyPath` option.
* added support for checking an array of types in `TypeValidator` * added support for checking an array of types in `TypeValidator`
* added a new `allowEmptyString` option to the `Length` constraint to allow rejecting empty strings when `min` is set, by setting it to `false`. * added a new `allowEmptyString` option to the `Length` constraint to allow rejecting empty strings when `min` is set, by setting it to `false`.
* Added new `minPropertyPath` and `maxPropertyPath` options * Added new `minPropertyPath` and `maxPropertyPath` options
to `Range` constraint in order to get the value to compare to `Range` constraint in order to get the value to compare
from an array or object from an array or object
* added the `min_limit_path` and `max_limit_path` parameters in violations when using * added the `min_limit_path` and `max_limit_path` parameters in violations when using
`Range` constraint with respectively the `minPropertyPath` and `Range` constraint with respectively the `minPropertyPath` and
`maxPropertyPath` options `maxPropertyPath` options
* added a new `notInRangeMessage` option to the `Range` constraint that will * added a new `notInRangeMessage` option to the `Range` constraint that will

View File

@ -59,13 +59,8 @@ class AddAutoMappingConfigurationPass implements CompilerPassInterface
$validatorBuilder = $container->getDefinition($this->validatorBuilderService); $validatorBuilder = $container->getDefinition($this->validatorBuilderService);
foreach ($container->findTaggedServiceIds($this->tag) as $id => $tags) { foreach ($container->findTaggedServiceIds($this->tag) as $id => $tags) {
$regexp = $this->getRegexp(array_merge($globalNamespaces, $servicesToNamespaces[$id] ?? [])); $regexp = $this->getRegexp(array_merge($globalNamespaces, $servicesToNamespaces[$id] ?? []));
if (null === $regexp) {
$container->removeDefinition($id);
continue;
}
$container->getDefinition($id)->setArgument('$classValidatorRegexp', $regexp);
$validatorBuilder->addMethodCall('addLoader', [new Reference($id)]); $validatorBuilder->addMethodCall('addLoader', [new Reference($id)]);
$container->getDefinition($id)->setArgument('$classValidatorRegexp', $regexp);
} }
$container->getParameterBag()->remove('validator.auto_mapping'); $container->getParameterBag()->remove('validator.auto_mapping');

View File

@ -29,6 +29,6 @@ trait AutoMappingTrait
} }
// Fallback on the config // Fallback on the config
return null === $classValidatorRegexp || preg_match($classValidatorRegexp, $metadata->getClassName()); return null !== $classValidatorRegexp && preg_match($classValidatorRegexp, $metadata->getClassName());
} }
} }

View File

@ -81,6 +81,6 @@ class AddAutoMappingConfigurationPassTest extends TestCase
(new AddAutoMappingConfigurationPass())->process($container); (new AddAutoMappingConfigurationPass())->process($container);
$this->assertFalse($container->hasDefinition('loader')); $this->assertNull($container->getDefinition('loader')->getArguments()['$classValidatorRegexp'] ?? null);
} }
} }

View File

@ -86,7 +86,7 @@ class PropertyInfoLoaderTest extends TestCase
)) ))
; ;
$propertyInfoLoader = new PropertyInfoLoader($propertyInfoStub, $propertyInfoStub, $propertyInfoStub); $propertyInfoLoader = new PropertyInfoLoader($propertyInfoStub, $propertyInfoStub, $propertyInfoStub, '{.*}');
$validator = Validation::createValidatorBuilder() $validator = Validation::createValidatorBuilder()
->enableAnnotationMapping() ->enableAnnotationMapping()
@ -197,7 +197,8 @@ class PropertyInfoLoaderTest extends TestCase
public function regexpProvider() public function regexpProvider()
{ {
return [ return [
[true, null], [false, null],
[true, '{.*}'],
[true, '{^'.preg_quote(PropertyInfoLoaderEntity::class).'$|^'.preg_quote(Entity::class).'$}'], [true, '{^'.preg_quote(PropertyInfoLoaderEntity::class).'$|^'.preg_quote(Entity::class).'$}'],
[false, '{^'.preg_quote(Entity::class).'$}'], [false, '{^'.preg_quote(Entity::class).'$}'],
]; ];
@ -217,7 +218,7 @@ class PropertyInfoLoaderTest extends TestCase
[new Type(Type::BUILTIN_TYPE_BOOL)] [new Type(Type::BUILTIN_TYPE_BOOL)]
); );
$propertyInfoLoader = new PropertyInfoLoader($propertyInfoStub, $propertyInfoStub, $propertyInfoStub); $propertyInfoLoader = new PropertyInfoLoader($propertyInfoStub, $propertyInfoStub, $propertyInfoStub, '{.*}');
$validator = Validation::createValidatorBuilder() $validator = Validation::createValidatorBuilder()
->enableAnnotationMapping() ->enableAnnotationMapping()
->addLoader($propertyInfoLoader) ->addLoader($propertyInfoLoader)