feature #25504 [Validator] Add option to pass custom values to Expression validator (ostrolucky)

This PR was merged into the 4.1-dev branch.

Discussion
----------

[Validator] Add option to pass custom values to Expression validator

| Q             | A
| ------------- | ---
| Branch?       | master
| Bug fix?      | no
| New feature?  | yes
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | -
| License       | MIT
| Doc PR        | -

I needed this in a Form. I had no way to pass things from `$options` into Expression validator.

Maybe can aid in https://github.com/symfony/symfony/pull/23134

Commits
-------

ba0565e3e8 [Validator] Add option to pass custom values to Expression validator
This commit is contained in:
Fabien Potencier 2018-01-08 13:57:43 +01:00
commit 445ce1d437
4 changed files with 17 additions and 1 deletions

View File

@ -5,6 +5,7 @@ CHANGELOG
-----
* Deprecated the `checkDNS` and `dnsMessage` options of the `Url` constraint. They will be removed in 5.0.
* added a `values` option to the `Expression` constraint
4.0.0
-----

View File

@ -30,6 +30,7 @@ class Expression extends Constraint
public $message = 'This value is not valid.';
public $expression;
public $values = array();
/**
* {@inheritdoc}

View File

@ -39,7 +39,7 @@ class ExpressionValidator extends ConstraintValidator
throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Expression');
}
$variables = array();
$variables = $constraint->values;
$variables['value'] = $value;
$variables['this'] = $this->context->getObject();

View File

@ -270,4 +270,18 @@ class ExpressionValidatorTest extends ConstraintValidatorTestCase
$this->assertTrue($used, 'Failed asserting that custom ExpressionLanguage instance is used.');
}
public function testPassingCustomValues()
{
$constraint = new Expression(array(
'expression' => 'value + custom == 2',
'values' => array(
'custom' => 1,
),
));
$this->validator->validate(1, $constraint);
$this->assertNoViolation();
}
}