cryonighter/validation-override-bundle
A Symfony bundle that allows dynamic modification of validation constraints at runtime via a provider pattern, without touching the validated class itself.
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:
When to consider alternatives:
#[Assert\When] or #[Assert\Callback]symfony/framework-bundle, symfony/validator)composer require cryonighter/validation-override-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.
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);
}
}
}
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.
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 }
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)
DynamicValidatorDecorator decorates the validator serviceSymfonyInternalsAccessor to locate and replace
the MetadataFactoryInterface property inside RecursiveValidator via reflectionDynamicMetadataFactory wraps the original factory — on each getMetadataFor() call it:
ClassMetadata (cached as usual by Symfony)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.
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.
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.
| Bundle version | PHP | Symfony |
|---|---|---|
| 0.x | ^8.2 | ^8.0 |
# 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
Please see CONTRIBUTING and CODE_OF_CONDUCT for details.
If you discover any security related issues, please email [email protected] instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.
How can I help you explore Laravel packages today?