bug #20122 [Validator] Reset constraint options (ro0NL)

This PR was merged into the 2.7 branch.

Discussion
----------

[Validator] Reset constraint options

| Q             | A
| ------------- | ---
| Branch?       | 2.7
| Bug fix?      | yes
| New feature?  | no
| BC breaks?    | no
| Deprecations? | no
| Tests pass?   | yes
| Fixed tickets | #20106
| License       | MIT
| Doc PR        | reference to the documentation PR, if any

I think it's good to reset the internal pointer of the options array if we depend on `key($options)`. I've added tests to clarify we intentionally check for the first key.

The current behavior actually differs for hhvm/php7 - https://3v4l.org/e6r6E

Commits
-------

4c6ddd4 reset constraint options
This commit is contained in:
Fabien Potencier 2016-10-02 08:50:33 -07:00
commit 80577f96bf
2 changed files with 34 additions and 0 deletions

View File

@ -129,6 +129,9 @@ abstract class Constraint
unset($options['value']);
}
if (is_array($options)) {
reset($options);
}
if (is_array($options) && count($options) > 0 && is_string(key($options))) {
foreach ($options as $option => $value) {
if (array_key_exists($option, $knownOptions)) {

View File

@ -206,4 +206,35 @@ class ConstraintTest extends \PHPUnit_Framework_TestCase
{
Constraint::getErrorName(1);
}
public function testOptionsAsDefaultOption()
{
$constraint = new ConstraintA($options = array('value1'));
$this->assertEquals($options, $constraint->property2);
$constraint = new ConstraintA($options = array('value1', 'property1' => 'value2'));
$this->assertEquals($options, $constraint->property2);
}
/**
* @expectedException \Symfony\Component\Validator\Exception\InvalidOptionsException
* @expectedExceptionMessage The options "0", "5" do not exist
*/
public function testInvalidOptions()
{
new ConstraintA(array('property2' => 'foo', 'bar', 5 => 'baz'));
}
public function testOptionsWithInvalidInternalPointer()
{
$options = array('property1' => 'foo');
next($options);
next($options);
$constraint = new ConstraintA($options);
$this->assertEquals('foo', $constraint->property1);
}
}