Skip to content

Commit

Permalink
bug #21053 [Validator] override property constraints in child class (…
Browse files Browse the repository at this point in the history
…xabbuh)

This PR was merged into the 2.7 branch.

Discussion
----------

[Validator] override property constraints in child class

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

Commits
-------

8b281fe override property constraints in child class
  • Loading branch information
fabpot committed Dec 26, 2016
2 parents a4ac1a7 + 8b281fe commit 0c1260c
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/Symfony/Component/Validator/Mapping/ClassMetadata.php
Expand Up @@ -346,6 +346,10 @@ public function mergeConstraints(ClassMetadata $source)
}

foreach ($source->getConstrainedProperties() as $property) {
if ($this->hasPropertyMetadata($property)) {
continue;
}

foreach ($source->getPropertyMetadata($property) as $member) {
$member = clone $member;

Expand Down
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\Validator\Tests\Mapping;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Constraints\GreaterThan;
use Symfony\Component\Validator\Constraints\Valid;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Tests\Fixtures\ConstraintA;
Expand Down Expand Up @@ -295,4 +296,29 @@ public function testGetPropertyMetadataReturnsEmptyArrayWithoutConfiguredMetadat
{
$this->assertCount(0, $this->metadata->getPropertyMetadata('foo'), '->getPropertyMetadata() returns an empty collection if no metadata is configured for the given property');
}

public function testMergeDoesOverrideConstraintsFromParentClassIfPropertyIsOverriddenInChildClass()
{
$parentMetadata = new ClassMetadata('\Symfony\Component\Validator\Tests\Mapping\ParentClass');
$parentMetadata->addPropertyConstraint('example', new GreaterThan(0));

$childMetadata = new ClassMetadata('\Symfony\Component\Validator\Tests\Mapping\ChildClass');
$childMetadata->addPropertyConstraint('example', new GreaterThan(1));
$childMetadata->mergeConstraints($parentMetadata);

$expectedMetadata = new ClassMetadata('\Symfony\Component\Validator\Tests\Mapping\ChildClass');
$expectedMetadata->addPropertyConstraint('example', new GreaterThan(1));

$this->assertEquals($expectedMetadata, $childMetadata);
}
}

class ParentClass
{
public $example = 0;
}

class ChildClass extends ParentClass
{
public $example = 1; // overrides parent property of same name
}

0 comments on commit 0c1260c

Please sign in to comment.