How to check if an element of an array is an array itself?

Given this input:

[ 'key' => 'value', ] 

How to check to:

  • key exists
  • Its value is an array (with any number of elements)

I expected this limitation to work

  $constraint = new Collection([ 'key' => new Required([ new Type('array'), new Collection([ 'value' => new Required([ new NotBlank(), ]), ]), ]), ]); 

but it throws an exception:

 Symfony\Component\Validator\Exception\UnexpectedTypeException: Expected argument of type "array or Traversable and ArrayAccess", "string" given 

What am I missing?

PS: this is symfony v2.7.1

PPS: just clarify: I know you can use a callback. If I wanted to re-run the check manually from scratch - I would not use symfony in the first place. Thus, we are talking, in particular, about combining existing constraints, and not about using a callback constraint.

+8
php symfony symfony-validator
source share
3 answers

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.

+4
source share

You say that the Collection constraint should just fail, not throw an exception, because 'value' is a string , not an array .

Symfony recently reported bug for this: https://github.com/symfony/symfony/issues/14943

+2
source share

Use the Callback constraint ( docs ) where you can implement your own validation logic.

Another way is to create custom constraint classes and validators. ( docs )

+1
source share

All Articles