opis / json-schema

JSON Schema validator for PHP
https://opis.io/json-schema
Apache License 2.0
567 stars 58 forks source link

Validation stops on first error #107

Open dontub opened 2 years ago

dontub commented 2 years ago

Currently the validation stops if an error occurs. https://github.com/opis/json-schema/blob/c48df6d7089a45f01e1c82432348f2d5976f9bfb/src/Schemas/ObjectSchema.php#L114 So if for example a required property is missing, the available properties are not validated at all. Actually we need to have all object properties/array items to be validated. Maybe it would make sense to have different maximum error limits:

dontub commented 2 years ago

For our project we are depending on this. (Not on the suggested error limits, though.) We'd like to avoid a custom fork so we would highly appreciate if a solution for this issue can be found.

Ping @sorinsarca :-)

dontub commented 2 years ago

This code in ObjectSchema would solve the issue:

protected function applyKeywords(array $keywords, ValidationContext $context): ?ValidationError
{
    $errors = [];
    foreach ($keywords as $keyword) {
        if (null !== ($error = $keyword->validate($context, $this))) {
            $errors[] = $error;
        }
    }

    if ([] === $errors) {
        return null;
    }

    if (1 === \count($errors)) {
        return $errors[0];
    }

    /** @var Schema $schema */
    $schema = $context->schema();

    return new ValidationError(
        'schema',
        $schema,
        DataInfo::fromContext($context),
        'The data does not match the schema',
        ['data' => $context->currentData()],
        $errors
    );
}

The part

if (1 === \count($errors)) {
    return $errors[0];
}

isn't necessary, though if there's only one error the behavior is as before.

Edit: Changed error message to not contain {data} because Opis\JsonSchema\Errors\ErrorFormatter doesn't support \stdClass: https://github.com/opis/json-schema/blob/c48df6d7089a45f01e1c82432348f2d5976f9bfb/src/Errors/ErrorFormatter.php#L231 (Showing the whole JSON in the error message probably makes no sense in most cases...)

matapatos commented 2 years ago

I agree with @dontub.

Tried code and works as a breeze! :D

aryojamousi commented 3 months ago

We have tried using the fork from @orakili and the code resolves the mentioned issue. It would be also highly appreciated if the fix get merged to master so we can also avoid using forks! :)

sunanzhi commented 2 months ago

Or this document may solve your problem?

https://opis.io/json-schema/2.x/php-validator.html#max-errors

image image

aryojamousi commented 2 months ago

We have actually set the max Errors to 100 in this case :( so I don't think that will have an impact. But I will give it a try with a lower number such as 5.

Edit: I just tried it with a lower number and the behaviour is still the unwanted one.