diff --git a/src/Symfony/Component/Validator/Context/ExecutionContext.php b/src/Symfony/Component/Validator/Context/ExecutionContext.php index beeef001e4..a02c587706 100644 --- a/src/Symfony/Component/Validator/Context/ExecutionContext.php +++ b/src/Symfony/Component/Validator/Context/ExecutionContext.php @@ -232,6 +232,14 @@ class ExecutionContext implements ExecutionContextInterface return $this->value; } + /** + * {@inheritdoc} + */ + public function getObject() + { + return $this->object; + } + /** * {@inheritdoc} */ diff --git a/src/Symfony/Component/Validator/Context/ExecutionContextInterface.php b/src/Symfony/Component/Validator/Context/ExecutionContextInterface.php index b0b8c2b97b..ab539fd81d 100644 --- a/src/Symfony/Component/Validator/Context/ExecutionContextInterface.php +++ b/src/Symfony/Component/Validator/Context/ExecutionContextInterface.php @@ -99,6 +99,20 @@ interface ExecutionContextInterface extends LegacyExecutionContextInterface */ public function getValidator(); + /** + * Returns the currently validated object. + * + * If the validator is currently validating a class constraint, the + * object of that class is returned. If it is a validating a property or + * getter constraint, the object that the property/getter belongs to is + * returned. + * + * In other cases, null is returned. + * + * @return object|null The currently validated object or null. + */ + public function getObject(); + /** * Sets the currently validated value. * diff --git a/src/Symfony/Component/Validator/Tests/Validator/Abstract2Dot5ApiTest.php b/src/Symfony/Component/Validator/Tests/Validator/Abstract2Dot5ApiTest.php index 8698df3845..0b011a4792 100644 --- a/src/Symfony/Component/Validator/Tests/Validator/Abstract2Dot5ApiTest.php +++ b/src/Symfony/Component/Validator/Tests/Validator/Abstract2Dot5ApiTest.php @@ -658,4 +658,24 @@ abstract class Abstract2Dot5ApiTest extends AbstractValidatorTest { $this->validate('Foobar'); } + + public function testAccessCurrentObject() + { + $test = $this; + $called = false; + $entity = new Entity(); + $entity->firstName = 'Bernhard'; + + $callback = function ($value, ExecutionContextInterface $context) use ($test, $entity, &$called) { + $called = true; + $test->assertSame($entity, $context->getObject()); + }; + + $this->metadata->addConstraint(new Callback($callback)); + $this->metadata->addPropertyConstraint('firstName', new Callback($callback)); + + $this->validator->validate($entity); + + $this->assertTrue($called); + } }