Skip to content

Checking for oneOf/anyOf with different types lose value when coercing types #533

Closed
@LordWeedlle

Description

@LordWeedlle

When checking for a schema which get a oneOf or an anyOf we validate type for each schema possible in JsonSchema/Constraints/TypeConstraint::validateType().
But inside this function, when using Constraint::CHECK_MODE_COERCE_TYPES option, we cast the $value (passed by reference to the function) to the type defined in schema which result in a NULL value set to $value this variable isn't castable to the required type.
When then checking for the good type, $value is NULL so it cannot validates.

Here is an example:

We wants to validate that we send a string 'all' or an array containing some strings.

$value = [
    'Monday'
];

$schema = [
    'type' => 'object',
    'properties' => [
        'daysOfWeek' => [
            'oneOf' => [
                [
                    'type' => 'string',
                    'enum' => 'all'
                ],
                [
                    'type'     => 'array',
                    'minItems' => 1,
                    'items'    => ['type' => 'string']
                ]
            ]
        ]
];

$validator  = new Validator;
// Cast to object
$value = json_decode(json_encode($value));

$validator->validate($value, $schema, Constraint::CHECK_MODE_COERCE_TYPES);

When validating the validator will cast $value to string in JsonSchema/Constraints/TypeConstraint.php:l222 ($value = $this->toString($value);). $value is then gonna equals NULL as the array cannot be casted to string. When then checking for second oneOf schema, it cannot validates.

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