4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Validator\Constraints;
14 use Symfony\Component\Validator\Constraint;
15 use Symfony\Component\Validator\ConstraintValidator;
16 use Symfony\Component\Validator\Exception\UnexpectedTypeException;
19 * @author Bernhard Schussek <bschussek@gmail.com>
21 class CollectionValidator extends ConstraintValidator
26 public function validate($value, Constraint $constraint)
28 if (!$constraint instanceof Collection) {
29 throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\Collection');
32 if (null === $value) {
36 if (!is_array($value) && !($value instanceof \Traversable && $value instanceof \ArrayAccess)) {
37 throw new UnexpectedTypeException($value, 'array or Traversable and ArrayAccess');
40 // We need to keep the initialized context when CollectionValidator
41 // calls itself recursively (Collection constraints can be nested).
42 // Since the context of the validator is overwritten when initialize()
43 // is called for the nested constraint, the outer validator is
44 // acting on the wrong context when the nested validation terminates.
46 // A better solution - which should be approached in Symfony 3.0 - is to
47 // remove the initialize() method and pass the context as last argument
48 // to validate() instead.
49 $context = $this->context;
51 foreach ($constraint->fields as $field => $fieldConstraint) {
52 // bug fix issue #2779
53 $existsInArray = is_array($value) && array_key_exists($field, $value);
54 $existsInArrayAccess = $value instanceof \ArrayAccess && $value->offsetExists($field);
56 if ($existsInArray || $existsInArrayAccess) {
57 if (count($fieldConstraint->constraints) > 0) {
58 $context->getValidator()
60 ->atPath('['.$field.']')
61 ->validate($value[$field], $fieldConstraint->constraints);
63 } elseif (!$fieldConstraint instanceof Optional && !$constraint->allowMissingFields) {
64 $context->buildViolation($constraint->missingFieldsMessage)
65 ->atPath('['.$field.']')
66 ->setParameter('{{ field }}', $this->formatValue($field))
67 ->setInvalidValue(null)
68 ->setCode(Collection::MISSING_FIELD_ERROR)
73 if (!$constraint->allowExtraFields) {
74 foreach ($value as $field => $fieldValue) {
75 if (!isset($constraint->fields[$field])) {
76 $context->buildViolation($constraint->extraFieldsMessage)
77 ->atPath('['.$field.']')
78 ->setParameter('{{ field }}', $this->formatValue($field))
79 ->setInvalidValue($fieldValue)
80 ->setCode(Collection::NO_SUCH_FIELD_ERROR)