Skip to content

Improve support for validation of optional data structures #35

@thibaudcolas

Description

@thibaudcolas

I'm trying and struggling to get the middleware working when validating data structures using optional objects. Here is an example of a JSON payload I'm working with:

{
  "payer" : {
    "id": 123,
    "company": {
      "id": 456
    },
  }
}

The tricky part here is with payer.company: I would like this to be optional – i.e. validate its attributes if it's there, but otherwise a payer with just an id is valid too. I haven't found a good way to do this with the way the middleware defines validators. The correct respect/Validation way would be to use keySet and key:

$validators = [
  'payer' => v::keySet(
    v::key('id', self::idValidator('must be a valid id'))
    v::key('company', v::keySet(
      v::key('id', self::idValidator('must be a valid id'))
    ), false)
  ),
];

This produces the following error list when payer.company is an empty object:

[
  'payer' => [
    'Must have keys { "id" }',
  ]
]

The error message is what I would expect, but since the middleware operates with a validator defined on payer, the messages' key set to "payer" does not point to what is causing the error. Generally, anything defined as a keySet causes this loss in accuracy of the error keys, since Slim-Validation has no awareness of how validators are defined within a keySet.

This might not be very problematic for a simple structure like this, but of course my real-world use case has a much bigger payload and more levels of nested objects. Is there anything I could do differently to make this work?

Metadata

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions