From a93a23adf0cd53ef50ca3b90356e9cc3598313cb Mon Sep 17 00:00:00 2001 From: Christian Flothmann Date: Sat, 4 May 2013 13:44:31 +0200 Subject: [PATCH] handle Optional and Required constraints from XML or YAML sources correctly --- .../Validator/Constraints/Collection.php | 6 +++ .../Tests/Constraints/CollectionTest.php | 39 +++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/src/Symfony/Component/Validator/Constraints/Collection.php b/src/Symfony/Component/Validator/Constraints/Collection.php index b618b41cc0b85..35e81037b105b 100644 --- a/src/Symfony/Component/Validator/Constraints/Collection.php +++ b/src/Symfony/Component/Validator/Constraints/Collection.php @@ -47,6 +47,12 @@ public function __construct($options = null) } foreach ($this->fields as $fieldName => $field) { + // the XmlFileLoader and YamlFileLoader pass the field Optional + // and Required constraint as an array with exactly one element + if (is_array($field) && count($field) == 1) { + $this->fields[$fieldName] = $field = $field[0]; + } + if (!$field instanceof Optional && !$field instanceof Required) { $this->fields[$fieldName] = $field = new Required($field); } diff --git a/src/Symfony/Component/Validator/Tests/Constraints/CollectionTest.php b/src/Symfony/Component/Validator/Tests/Constraints/CollectionTest.php index e2998689ac884..c60b65e541d31 100644 --- a/src/Symfony/Component/Validator/Tests/Constraints/CollectionTest.php +++ b/src/Symfony/Component/Validator/Tests/Constraints/CollectionTest.php @@ -14,6 +14,7 @@ use Symfony\Component\Validator\Constraints\Collection; use Symfony\Component\Validator\Constraints\Collection\Required; use Symfony\Component\Validator\Constraints\Collection\Optional; +use Symfony\Component\Validator\Constraints\Email; use Symfony\Component\Validator\Constraints\Valid; /** @@ -70,4 +71,42 @@ public function testRejectValidConstraintWithinRequired() 'foo' => new Required(new Valid()), )); } + + public function testAcceptOptionalConstraintAsOneElementArray() + { + $collection1 = new Collection(array( + "fields" => array( + "alternate_email" => array( + new Optional(new Email()), + ), + ), + )); + + $collection2 = new Collection(array( + "fields" => array( + "alternate_email" => new Optional(new Email()), + ), + )); + + $this->assertEquals($collection1, $collection2); + } + + public function testAcceptRequiredConstraintAsOneElementArray() + { + $collection1 = new Collection(array( + "fields" => array( + "alternate_email" => array( + new Required(new Email()), + ), + ), + )); + + $collection2 = new Collection(array( + "fields" => array( + "alternate_email" => new Required(new Email()), + ), + )); + + $this->assertEquals($collection1, $collection2); + } }