I had the exact problem two nights ago.
The conclusion at the very end was that the Symfony2 validation does not have a "fast reject" check. That is, even if your Type() constraint fails, it will continue with other constraints, and thus end with an UnexpectedTypeException exception.
However, I was able to find a way to solve this problem:
$constraint = new Collection([ 'key' => new Required([ new Type(['type' => 'array']), new Collection([ // Need to wrap fields into this // in order to provide "groups" 'fields' => [ 'value' => new Required([ new NotBlank(), ]), ], 'groups' => 'phase2' // <-- THIS IS CRITICAL ]), ]), ]); // In your controller, service, etc... $V = $this->get('validator'); // Checks everything by `Collection` marked with special group $violations = $V->validate($data, $constraint); if ( $violations->count()){ // Do something } // Checks *only* "phase2" group constraints $violations = $V->validate($data, $constraint, 'phase2'); if ( $violations->count()){ // Do something }
Hope this helps a bit. Personally, I am annoyed that we need to do this. Some kind of fast-fail flag in the validator service would be very useful.
Jovan perovic
source share