cryonighter / validation-override-bundle
Symfony bundle for dynamic validation constraint modification via provider pattern
Package info
github.com/cryonighter/validation-override-bundle
Type:symfony-bundle
pkg:composer/cryonighter/validation-override-bundle
Requires
- php: >=8.2
- symfony/framework-bundle: ^8.0
- symfony/validator: ^8.0
Requires (Dev)
- phpunit/phpunit: ^11.0
- symfony/messenger: ^8.0
- symfony/phpunit-bridge: ^8.0
This package is auto-updated.
Last update: 2026-08-11 09:15:41 UTC
README
A Symfony bundle that allows dynamic modification of validation constraints at runtime via a provider pattern, without touching the validated class itself.
Description
Symfony's validator loads constraints from PHP attributes, YAML, or XML and caches them. There is no standard extension point to modify these constraints dynamically — for example, based on runtime conditions, environment flags, or external configuration.
This bundle solves this by intercepting the validator's metadata factory and passing
the loaded ClassMetadata through a chain of DynamicRulesProviderInterface providers
before validation occurs. Each provider can add, remove, or replace constraints for a specific class.
When this bundle is appropriate:
- The validated class belongs to a vendor package and cannot be modified
- Validation rules depend on runtime context (database config, tenant settings, environment flags)
- You want to keep the class clean for the common case and override rules only in specific scenarios
When to consider alternatives:
- The class is yours — use validation groups or a second DTO
- The condition is static — use
#[Assert\When]or#[Assert\Callback] - The team is large — the implicit nature of providers increases cognitive overhead
Requirements
- PHP >= 8.2.0 but the latest stable version of PHP is recommended
- Symfony 8.0 or higher (
symfony/framework-bundle,symfony/validator)
Installation
1. Install via Composer
composer require cryonighter/validation-override-bundle
2. Register the bundle
If Symfony Flex did not register the bundle automatically, add it manually:
// config/bundles.php return [ // ... Cryonighter\ValidationOverrideBundle\ValidationOverrideBundle::class => ['all' => true], ];
No additional configuration is required. The bundle registers the validator decorator automatically.
Usage
Step 1 — Create a provider
Implement DynamicRulesProviderInterface. The bundle will auto-tag all implementations
via _instanceof — no services.yaml entry is needed unless you require a specific priority.
namespace App\Validator; use App\Dto\MyDto; use Cryonighter\ValidationOverrideBundle\Validator\DynamicRulesProviderInterface; use Symfony\Component\Validator\Constraints as Assert; use Symfony\Component\Validator\Mapping\ClassMetadata; class MyClassRulesProvider implements DynamicRulesProviderInterface { public function supports(string $className): bool { return $className === MyDto::class; } public function modify(ClassMetadata $metadata): void { // Add a constraint $metadata->addPropertyConstraint('email', new Assert\Email()); // Remove a constraint type from a property $this->removeConstraint($metadata, 'name', Assert\NotBlank::class); } private function removeConstraint(ClassMetadata $metadata, string $property, string $constraintClass): void { foreach ($metadata->getPropertyMetadata($property) as $memberMetadata) { $ref = new \ReflectionClass(\Symfony\Component\Validator\Mapping\GenericMetadata::class); $constraintsProp = $ref->getProperty('constraints'); $constraintsProp->setValue($memberMetadata, array_values(array_filter( $constraintsProp->getValue($memberMetadata), fn($c) => !($c instanceof $constraintClass), ))); $byGroupProp = $ref->getProperty('constraintsByGroup'); $byGroup = $byGroupProp->getValue($memberMetadata); foreach ($byGroup as $group => $groupConstraints) { $byGroup[$group] = array_values(array_filter( $groupConstraints, fn($c) => !($c instanceof $constraintClass), )); } $byGroupProp->setValue($memberMetadata, $byGroup); } } }
Step 2 — Use the validator as usual
No changes to your validation call are required:
use Symfony\Component\Validator\Validator\ValidatorInterface; class MyService { public function __construct(private readonly ValidatorInterface $validator) {} public function process(MyDto $dto): void { $violations = $this->validator->validate($dto); // ... } }
The bundle transparently intercepts the validation pipeline and applies your providers.
Controlling provider order
If multiple providers modify the same class, use priority to define the order.
Higher priority runs first:
# config/services.yaml App\Validator\FirstProvider: tags: - { name: cryonighter.validation_override.rules_provider, priority: 10 } App\Validator\SecondProvider: tags: - { name: cryonighter.validation_override.rules_provider, priority: 5 }
How It Works
Symfony builds the validator via ValidatorBuilder::getValidator() internally.
The resulting LazyLoadingMetadataFactory is not exposed as a standalone service
in the DI container and cannot be decorated via standard Symfony means.
This bundle works around this limitation with the following approach:
validator (DI alias)
└── DynamicValidatorDecorator ← decorates "validator" service
└── TraceableValidator (inner)
└── RecursiveValidator
└── DynamicMetadataFactory ← injected via reflection on first call
└── LazyLoadingMetadataFactory (original)
DynamicValidatorDecoratordecorates thevalidatorservice- On the first validation call, it uses
SymfonyInternalsAccessorto locate and replace theMetadataFactoryInterfaceproperty insideRecursiveValidatorvia reflection DynamicMetadataFactorywraps the original factory — on eachgetMetadataFor()call it:- Asks the original factory for
ClassMetadata(cached as usual by Symfony) - Deep-clones the metadata so providers never mutate the cached original
- Passes the clone through all matching providers
- Returns the modified clone to the validator
- Asks the original factory for
Limitations and Caveats
Implicit behavior
Providers are invisible to standard Symfony tooling. php bin/console debug:validator
will show the original constraints defined on the class, not the modified ones.
This is the main trade-off of this approach — document your providers thoroughly.
Reflection over Symfony internals
SymfonyInternalsAccessor uses reflection on private properties of TraceableValidator
and RecursiveValidator. These are internal implementation details of Symfony and
may change in any release. See UPGRADE.md for the compatibility checklist.
Provider isolation
Each provider receives a fresh deep clone of the original ClassMetadata.
However, if two providers modify the same property of the same class,
the second provider's changes will overwrite the first's — use priority to make the order explicit.
Providers that operate on different properties do not interfere with each other.
Compatibility
| Bundle version | PHP | Symfony |
|---|---|---|
| 0.x | ^8.2 | ^8.0 |
Testing
# All tests ./vendor/bin/phpunit # Only unit ./vendor/bin/phpunit --testsuite Unit # Only integration ./vendor/bin/phpunit --testsuite Integration # Specific file ./vendor/bin/phpunit tests/Integration/DynamicValidatorDecoratorTest.php # With coating (requires Xdebug or PCOV) ./vendor/bin/phpunit --coverage-text
Contributing
Please see CONTRIBUTING and CODE_OF_CONDUCT for details.
Security
If you discover any security related issues, please email cryonighter@yandex.ru instead of using the issue tracker.
Credits
License
The MIT License (MIT). Please see License File for more information.