Skip to content

Oneof/AnyOf/AllOf applied to the properties of an object #393

Closed
@CMCDragonkai

Description

@CMCDragonkai

I have tried these schemas based on these answers:

But I can't get them to work:

<?php

use JsonSchema\Validator;
use JsonSchema\Constraints\Constraint;
use JsonSchema\Exception\ValidationException;

$validator = new Validator;

$data = file_get_contents('./test.json');

$data = json_decode($data, true);

$validator->validate(
    $data,
    json_decode(json_encode([
        'type' => 'object',
        'properties' => [
            'response' => [
                'type' => 'object',
                'oneOf' => [
                    ['required' => ['error']],
                    ['required' => ['result']]
                ],
                'properties' => [
                    'error' => [
                        'type' => 'object'
                    ],
                    'result' => [
                        'type' => 'object'
                    ]
                ]
            ]
        ],
        'required' => ['response']
    ])),
    Constraint::CHECK_MODE_TYPE_CAST | Constraint::CHECK_MODE_EXCEPTIONS
);

var_dump($validator->isValid());
// JsonSchema\Exception\ValidationException with message 'Error validating /response/error: The property error is required'
<?php

use JsonSchema\Validator;
use JsonSchema\Constraints\Constraint;
use JsonSchema\Exception\ValidationException;

$validator = new Validator;

$data = file_get_contents('./test.json');

$data = json_decode($data, true);

$validator->validate(
    $data,
    json_decode(json_encode([
        'type' => 'object',
        'properties' => [
            'response' => [
                'type' => 'object',
                'oneOf' => [
                    [
                        'properties' => [
                            'error' => [
                                'type' => 'object'
                            ],
                        ]
                    ],
                    [
                        'properties' => [
                            'result' => [
                                'type' => 'object'
                            ],
                        ],
                    ]
                ]
            ]
        ],
        'required' => ['response']
    ])),
    Constraint::CHECK_MODE_TYPE_CAST | Constraint::CHECK_MODE_EXCEPTIONS
);

var_dump($validator->isValid());
// JsonSchema\Exception\ValidationException with message 'Error validating /response: Failed to match exactly one schema'

The data is like:

{
    "response": {
        "result": {}
    }
}
{
    "response": {
        "error": {}
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions