Skip to content

[Validator] Let option values reference values in the object graph #7726

Closed
@webmozart

Description

@webmozart

In #790 and #7444 the need to reference dynamic values in constraint options was discovered. A simple example:

use Symfony\Component\Validator\Constraints\Range;
use Symfony\Component\Validator\Constraints\Reference;

/**
 * @Range(min = @Reference("min"), max = @Reference("max"))
 */
private $value;

private $min;

private $max

Here, the values of the "min" and "max" option are determined at runtime. References can contain any valid property path.

XML example:

<property name="value">
    <constraint name="Range">
        <option name="min" reference="min" />
        <option name="max" reference="max" />
    </constraint>
</property>

YAML example:

properties:
    value:
        - Range:
            min: @min

Attention: This example would be consistent with the DIC YAML syntax for service references, but it would be incompatible for options where values starting with "@" are valid expected values. Is this a problem?

PHP example:

$metadata->addPropertyConstraint('value', new Range(array(
    'min' => new Reference('min'),
    'max' => new Reference('max'),
)));

Some implementation hints:

Class Reference should be an annotation but not inherit from Constraint (it is no constraint). It probably needs only a constructor. Additionally, we need a ReferenceResolver (and ReferenceResolverInterface, of course) that receives a PropertyAccessorInterface in its constructor. It needs only a method resolveReference(Reference $reference, ExecutionContextInterface $context) that returns the value of a reference based on the current state of the execution context.

All validators that support references then need the ReferenceResolver to resolve any Reference instances when they find them.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions