diff --git a/README.md b/README.md index 938b77d9..06f58ebd 100644 --- a/README.md +++ b/README.md @@ -211,6 +211,7 @@ third argument to `Validator::validate()`, or can be provided as the third argum | `Constraint::CHECK_MODE_DISABLE_FORMAT` | Do not validate "format" constraints | | `Constraint::CHECK_MODE_VALIDATE_SCHEMA` | Validate the schema as well as the provided document | | `Constraint::CHECK_MODE_STRICT` [^3] | Validate the scheme using strict mode using the specified draft | +| `Constraint::CHECK_MODE_FAIL_FAST` [^4] | Stop at the first error, only one error is reported | [^1]: Please note that using `CHECK_MODE_COERCE_TYPES` or `CHECK_MODE_APPLY_DEFAULTS` will modify your original data. @@ -218,6 +219,8 @@ original data. enabled, the validator will use (and coerce) the first compatible type it encounters, even if the schema defines another type that matches directly and does not require coercion. [^3]: `CHECK_MODE_STRICT` only can be used for Draft-6, Draft 7 or Draft 2019-09 at this point. +[^4]: `CHECK_MODE_FAIL_FAST` only has an effect in combination with `CHECK_MODE_STRICT`. Use it when only the validity of +the data is needed, as validation can then skip the rest of the data once an error is found. ## Running the tests diff --git a/phpstan-baseline.neon b/phpstan-baseline.neon index 0e1bcafb..1152bd78 100644 --- a/phpstan-baseline.neon +++ b/phpstan-baseline.neon @@ -71,12 +71,12 @@ parameters: path: src/JsonSchema/Constraints/Factory.php - - message: "#^Method JsonSchema\\\\Constraints\\\\Factory\\:\\:getConfig\\(\\) should return int\\<0, 1023\\> but returns int\\.$#" + message: "#^Method JsonSchema\\\\Constraints\\\\Factory\\:\\:getConfig\\(\\) should return int\\<0, 2047\\> but returns int\\.$#" count: 1 path: src/JsonSchema/Constraints/Factory.php - - message: "#^Property JsonSchema\\\\Constraints\\\\Factory\\:\\:\\$checkMode \\(int\\<0, 1023\\>\\) does not accept int\\.$#" + message: "#^Property JsonSchema\\\\Constraints\\\\Factory\\:\\:\\$checkMode \\(int\\<0, 2047\\>\\) does not accept int\\.$#" count: 2 path: src/JsonSchema/Constraints/Factory.php diff --git a/src/JsonSchema/Constraints/Constraint.php b/src/JsonSchema/Constraints/Constraint.php index 7538ad67..1b309155 100644 --- a/src/JsonSchema/Constraints/Constraint.php +++ b/src/JsonSchema/Constraints/Constraint.php @@ -23,6 +23,7 @@ abstract class Constraint extends BaseConstraint implements ConstraintInterface public const CHECK_MODE_ONLY_REQUIRED_DEFAULTS = 0x00000080; public const CHECK_MODE_VALIDATE_SCHEMA = 0x00000100; public const CHECK_MODE_STRICT = 0x00000200; + public const CHECK_MODE_FAIL_FAST = 0x00000400; /** * Bubble down the path diff --git a/src/JsonSchema/Constraints/Drafts/Draft06/AnyOfConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft06/AnyOfConstraint.php index 29b0f29b..eabde54b 100644 --- a/src/JsonSchema/Constraints/Drafts/Draft06/AnyOfConstraint.php +++ b/src/JsonSchema/Constraints/Drafts/Draft06/AnyOfConstraint.php @@ -29,6 +29,30 @@ public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = n return; } + // Only the validity of each branch is needed to know whether any of them matches. The errors of the + // branches are collected afterwards, by evaluating them once more, only if the anyOf fails. + $previousFailFast = $this->factory->startFailFast(); + if ($previousFailFast !== null) { + try { + foreach ($schema->anyOf as $anyOfSchema) { + $schemaConstraint = $this->factory->createInstanceFor('schema'); + $schemaConstraint->check($value, $anyOfSchema, $path, $i); + if ($schemaConstraint->isValid()) { + return; + } + } + } finally { + $this->factory->stopFailFast($previousFailFast); + } + + if ($previousFailFast) { + // Only the validity of this anyOf is needed as well + $this->addError(ConstraintError::ANY_OF(), $path); + + return; + } + } + foreach ($schema->anyOf as $anyOfSchema) { $schemaConstraint = $this->factory->createInstanceFor('schema'); diff --git a/src/JsonSchema/Constraints/Drafts/Draft06/Draft06Constraint.php b/src/JsonSchema/Constraints/Drafts/Draft06/Draft06Constraint.php index 2903f0c8..de2a29f8 100644 --- a/src/JsonSchema/Constraints/Drafts/Draft06/Draft06Constraint.php +++ b/src/JsonSchema/Constraints/Drafts/Draft06/Draft06Constraint.php @@ -17,11 +17,17 @@ class Draft06Constraint extends Constraint { public function __construct(?\JsonSchema\Constraints\Factory $factory = null) { - parent::__construct(new Factory( + $draftFactory = new Factory( $factory ? $factory->getSchemaStorage() : new SchemaStorage(), $factory ? $factory->getUriRetriever() : new UriRetriever(), $factory ? $factory->getConfig() : Constraint::CHECK_MODE_NORMAL - )); + ); + if ($factory) { + // Nested schemas take part in the evaluation of the schema they belong to + $draftFactory->setEvaluationState($factory->getEvaluationState()); + } + + parent::__construct($draftFactory); } public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void @@ -134,6 +140,11 @@ private function validateSchema($schema, ?JsonPointer $path): void */ protected function checkForKeyword(string $keyword, $value, $schema = null, ?JsonPointer $path = null, $i = null): void { + // The schema is invalid already, and only its validity is needed + if ($this->numErrors() > 0 && $this->factory->isFailFast()) { + return; + } + $validator = $this->factory->createInstanceFor($keyword); $validator->check($value, $schema, $path, $i); diff --git a/src/JsonSchema/Constraints/Drafts/Draft06/ItemsConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft06/ItemsConstraint.php index 3b52465a..ad2a709d 100644 --- a/src/JsonSchema/Constraints/Drafts/Draft06/ItemsConstraint.php +++ b/src/JsonSchema/Constraints/Drafts/Draft06/ItemsConstraint.php @@ -49,6 +49,9 @@ public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = n } $this->addErrors($schemaConstraint->getErrors()); + if ($this->factory->isFailFast()) { + return; + } } } } diff --git a/src/JsonSchema/Constraints/Drafts/Draft06/NotConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft06/NotConstraint.php index 2a8268e1..fdbc576a 100644 --- a/src/JsonSchema/Constraints/Drafts/Draft06/NotConstraint.php +++ b/src/JsonSchema/Constraints/Drafts/Draft06/NotConstraint.php @@ -28,8 +28,16 @@ public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = n return; } - $schemaConstraint = $this->factory->createInstanceFor('schema'); - $schemaConstraint->check($value, $schema->not, $path, $i); + // Only the validity of the subschema is needed, its errors are never reported + $previousFailFast = $this->factory->startFailFast(); + try { + $schemaConstraint = $this->factory->createInstanceFor('schema'); + $schemaConstraint->check($value, $schema->not, $path, $i); + } finally { + if ($previousFailFast !== null) { + $this->factory->stopFailFast($previousFailFast); + } + } if (!$schemaConstraint->isValid()) { return; diff --git a/src/JsonSchema/Constraints/Drafts/Draft06/OneOfConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft06/OneOfConstraint.php index cd8efd94..31cf3239 100644 --- a/src/JsonSchema/Constraints/Drafts/Draft06/OneOfConstraint.php +++ b/src/JsonSchema/Constraints/Drafts/Draft06/OneOfConstraint.php @@ -28,6 +28,35 @@ public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = n return; } + // Only the validity of each branch is needed to know whether exactly one of them matches. The errors of + // the branches are collected afterwards, by evaluating them once more, only if the oneOf fails. + $previousFailFast = $this->factory->startFailFast(); + if ($previousFailFast !== null) { + $matchedSchema = 0; + try { + foreach ($schema->oneOf as $oneOfSchema) { + $schemaConstraint = $this->factory->createInstanceFor('schema'); + $schemaConstraint->check($value, $oneOfSchema, $path, $i); + if ($schemaConstraint->isValid()) { + $matchedSchema++; + } + } + } finally { + $this->factory->stopFailFast($previousFailFast); + } + + if ($matchedSchema === 1) { + return; + } + + if ($previousFailFast) { + // Only the validity of this oneOf is needed as well + $this->addError(ConstraintError::ONE_OF(), $path); + + return; + } + } + $matchedSchema = 0; foreach ($schema->oneOf as $oneOfSchema) { $schemaConstraint = $this->factory->createInstanceFor('schema'); diff --git a/src/JsonSchema/Constraints/Drafts/Draft06/PropertiesConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft06/PropertiesConstraint.php index 403b05b2..22fc132f 100644 --- a/src/JsonSchema/Constraints/Drafts/Draft06/PropertiesConstraint.php +++ b/src/JsonSchema/Constraints/Drafts/Draft06/PropertiesConstraint.php @@ -46,6 +46,9 @@ public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = n } $this->addErrors($schemaConstraint->getErrors()); + if ($this->factory->isFailFast()) { + return; + } } } } diff --git a/src/JsonSchema/Constraints/Drafts/Draft07/AnyOfConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft07/AnyOfConstraint.php index 85242962..e6a4b8f4 100644 --- a/src/JsonSchema/Constraints/Drafts/Draft07/AnyOfConstraint.php +++ b/src/JsonSchema/Constraints/Drafts/Draft07/AnyOfConstraint.php @@ -29,6 +29,30 @@ public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = n return; } + // Only the validity of each branch is needed to know whether any of them matches. The errors of the + // branches are collected afterwards, by evaluating them once more, only if the anyOf fails. + $previousFailFast = $this->factory->startFailFast(); + if ($previousFailFast !== null) { + try { + foreach ($schema->anyOf as $anyOfSchema) { + $schemaConstraint = $this->factory->createInstanceFor('schema'); + $schemaConstraint->check($value, $anyOfSchema, $path, $i); + if ($schemaConstraint->isValid()) { + return; + } + } + } finally { + $this->factory->stopFailFast($previousFailFast); + } + + if ($previousFailFast) { + // Only the validity of this anyOf is needed as well + $this->addError(ConstraintError::ANY_OF(), $path); + + return; + } + } + foreach ($schema->anyOf as $anyOfSchema) { $schemaConstraint = $this->factory->createInstanceFor('schema'); diff --git a/src/JsonSchema/Constraints/Drafts/Draft07/Draft07Constraint.php b/src/JsonSchema/Constraints/Drafts/Draft07/Draft07Constraint.php index 773150ba..f4458d27 100644 --- a/src/JsonSchema/Constraints/Drafts/Draft07/Draft07Constraint.php +++ b/src/JsonSchema/Constraints/Drafts/Draft07/Draft07Constraint.php @@ -17,11 +17,17 @@ class Draft07Constraint extends Constraint { public function __construct(?\JsonSchema\Constraints\Factory $factory = null) { - parent::__construct(new Factory( + $draftFactory = new Factory( $factory ? $factory->getSchemaStorage() : new SchemaStorage(), $factory ? $factory->getUriRetriever() : new UriRetriever(), $factory ? $factory->getConfig() : Constraint::CHECK_MODE_NORMAL - )); + ); + if ($factory) { + // Nested schemas take part in the evaluation of the schema they belong to + $draftFactory->setEvaluationState($factory->getEvaluationState()); + } + + parent::__construct($draftFactory); } public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void @@ -136,6 +142,11 @@ private function validateSchema($schema, ?JsonPointer $path): void */ protected function checkForKeyword(string $keyword, $value, $schema = null, ?JsonPointer $path = null, $i = null): void { + // The schema is invalid already, and only its validity is needed + if ($this->numErrors() > 0 && $this->factory->isFailFast()) { + return; + } + $validator = $this->factory->createInstanceFor($keyword); $validator->check($value, $schema, $path, $i); diff --git a/src/JsonSchema/Constraints/Drafts/Draft07/IfThenElseConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft07/IfThenElseConstraint.php index d3fe82c7..20806b50 100644 --- a/src/JsonSchema/Constraints/Drafts/Draft07/IfThenElseConstraint.php +++ b/src/JsonSchema/Constraints/Drafts/Draft07/IfThenElseConstraint.php @@ -31,7 +31,15 @@ public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = n $ifSchema = $schema->if; if (!is_bool($ifSchema)) { - $schemaConstraint->check($value, $ifSchema, $path, $i); + // Only the validity of the if subschema is needed, its errors are never reported + $previousFailFast = $this->factory->startFailFast(); + try { + $schemaConstraint->check($value, $ifSchema, $path, $i); + } finally { + if ($previousFailFast !== null) { + $this->factory->stopFailFast($previousFailFast); + } + } $meetsIfConditions = $schemaConstraint->isValid(); $schemaConstraint->reset(); } else { diff --git a/src/JsonSchema/Constraints/Drafts/Draft07/ItemsConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft07/ItemsConstraint.php index 5b94ab4f..73464830 100644 --- a/src/JsonSchema/Constraints/Drafts/Draft07/ItemsConstraint.php +++ b/src/JsonSchema/Constraints/Drafts/Draft07/ItemsConstraint.php @@ -49,6 +49,9 @@ public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = n } $this->addErrors($schemaConstraint->getErrors()); + if ($this->factory->isFailFast()) { + return; + } } } } diff --git a/src/JsonSchema/Constraints/Drafts/Draft07/NotConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft07/NotConstraint.php index fdba81bf..d8948aa0 100644 --- a/src/JsonSchema/Constraints/Drafts/Draft07/NotConstraint.php +++ b/src/JsonSchema/Constraints/Drafts/Draft07/NotConstraint.php @@ -28,8 +28,16 @@ public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = n return; } - $schemaConstraint = $this->factory->createInstanceFor('schema'); - $schemaConstraint->check($value, $schema->not, $path, $i); + // Only the validity of the subschema is needed, its errors are never reported + $previousFailFast = $this->factory->startFailFast(); + try { + $schemaConstraint = $this->factory->createInstanceFor('schema'); + $schemaConstraint->check($value, $schema->not, $path, $i); + } finally { + if ($previousFailFast !== null) { + $this->factory->stopFailFast($previousFailFast); + } + } if (!$schemaConstraint->isValid()) { return; diff --git a/src/JsonSchema/Constraints/Drafts/Draft07/OneOfConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft07/OneOfConstraint.php index 4523f73c..ae06baf9 100644 --- a/src/JsonSchema/Constraints/Drafts/Draft07/OneOfConstraint.php +++ b/src/JsonSchema/Constraints/Drafts/Draft07/OneOfConstraint.php @@ -28,6 +28,35 @@ public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = n return; } + // Only the validity of each branch is needed to know whether exactly one of them matches. The errors of + // the branches are collected afterwards, by evaluating them once more, only if the oneOf fails. + $previousFailFast = $this->factory->startFailFast(); + if ($previousFailFast !== null) { + $matchedSchema = 0; + try { + foreach ($schema->oneOf as $oneOfSchema) { + $schemaConstraint = $this->factory->createInstanceFor('schema'); + $schemaConstraint->check($value, $oneOfSchema, $path, $i); + if ($schemaConstraint->isValid()) { + $matchedSchema++; + } + } + } finally { + $this->factory->stopFailFast($previousFailFast); + } + + if ($matchedSchema === 1) { + return; + } + + if ($previousFailFast) { + // Only the validity of this oneOf is needed as well + $this->addError(ConstraintError::ONE_OF(), $path); + + return; + } + } + $matchedSchema = 0; foreach ($schema->oneOf as $oneOfSchema) { $schemaConstraint = $this->factory->createInstanceFor('schema'); diff --git a/src/JsonSchema/Constraints/Drafts/Draft07/PropertiesConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft07/PropertiesConstraint.php index 2abad178..ba1efecb 100644 --- a/src/JsonSchema/Constraints/Drafts/Draft07/PropertiesConstraint.php +++ b/src/JsonSchema/Constraints/Drafts/Draft07/PropertiesConstraint.php @@ -46,6 +46,9 @@ public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = n } $this->addErrors($schemaConstraint->getErrors()); + if ($this->factory->isFailFast()) { + return; + } } } } diff --git a/src/JsonSchema/Constraints/Drafts/Draft2019/AnyOfConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft2019/AnyOfConstraint.php index f0b66049..7fb70a53 100644 --- a/src/JsonSchema/Constraints/Drafts/Draft2019/AnyOfConstraint.php +++ b/src/JsonSchema/Constraints/Drafts/Draft2019/AnyOfConstraint.php @@ -29,6 +29,30 @@ public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = n return; } + // Only the validity of each branch is needed to know whether any of them matches. The errors of the + // branches are collected afterwards, by evaluating them once more, only if the anyOf fails. + $previousFailFast = $this->factory->startFailFast(); + if ($previousFailFast !== null) { + try { + foreach ($schema->anyOf as $anyOfSchema) { + $schemaConstraint = $this->factory->createInstanceFor('schema'); + $schemaConstraint->check($value, $anyOfSchema, $path, $i); + if ($schemaConstraint->isValid()) { + return; + } + } + } finally { + $this->factory->stopFailFast($previousFailFast); + } + + if ($previousFailFast) { + // Only the validity of this anyOf is needed as well + $this->addError(ConstraintError::ANY_OF(), $path); + + return; + } + } + foreach ($schema->anyOf as $anyOfSchema) { $schemaConstraint = $this->factory->createInstanceFor('schema'); diff --git a/src/JsonSchema/Constraints/Drafts/Draft2019/Draft2019Constraint.php b/src/JsonSchema/Constraints/Drafts/Draft2019/Draft2019Constraint.php index b5cbc10a..28aa1629 100644 --- a/src/JsonSchema/Constraints/Drafts/Draft2019/Draft2019Constraint.php +++ b/src/JsonSchema/Constraints/Drafts/Draft2019/Draft2019Constraint.php @@ -17,11 +17,17 @@ class Draft2019Constraint extends Constraint { public function __construct(?\JsonSchema\Constraints\Factory $factory = null) { - parent::__construct(new Factory( + $draftFactory = new Factory( $factory ? $factory->getSchemaStorage() : new SchemaStorage(), $factory ? $factory->getUriRetriever() : new UriRetriever(), $factory ? $factory->getConfig() : Constraint::CHECK_MODE_NORMAL - )); + ); + if ($factory) { + // Nested schemas take part in the evaluation of the schema they belong to + $draftFactory->setEvaluationState($factory->getEvaluationState()); + } + + parent::__construct($draftFactory); } public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void @@ -136,6 +142,11 @@ private function validateSchema($schema, ?JsonPointer $path): void */ protected function checkForKeyword(string $keyword, $value, $schema = null, ?JsonPointer $path = null, $i = null): void { + // The schema is invalid already, and only its validity is needed + if ($this->numErrors() > 0 && $this->factory->isFailFast()) { + return; + } + $validator = $this->factory->createInstanceFor($keyword); $validator->check($value, $schema, $path, $i); diff --git a/src/JsonSchema/Constraints/Drafts/Draft2019/IfThenElseConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft2019/IfThenElseConstraint.php index a9451420..7960485b 100644 --- a/src/JsonSchema/Constraints/Drafts/Draft2019/IfThenElseConstraint.php +++ b/src/JsonSchema/Constraints/Drafts/Draft2019/IfThenElseConstraint.php @@ -31,7 +31,15 @@ public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = n $ifSchema = $schema->if; if (!is_bool($ifSchema)) { - $schemaConstraint->check($value, $ifSchema, $path, $i); + // Only the validity of the if subschema is needed, its errors are never reported + $previousFailFast = $this->factory->startFailFast(); + try { + $schemaConstraint->check($value, $ifSchema, $path, $i); + } finally { + if ($previousFailFast !== null) { + $this->factory->stopFailFast($previousFailFast); + } + } $meetsIfConditions = $schemaConstraint->isValid(); $schemaConstraint->reset(); } else { diff --git a/src/JsonSchema/Constraints/Drafts/Draft2019/ItemsConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft2019/ItemsConstraint.php index 38abb3df..de7a02ee 100644 --- a/src/JsonSchema/Constraints/Drafts/Draft2019/ItemsConstraint.php +++ b/src/JsonSchema/Constraints/Drafts/Draft2019/ItemsConstraint.php @@ -49,6 +49,9 @@ public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = n } $this->addErrors($schemaConstraint->getErrors()); + if ($this->factory->isFailFast()) { + return; + } } } } diff --git a/src/JsonSchema/Constraints/Drafts/Draft2019/NotConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft2019/NotConstraint.php index 8b9b40bd..95674257 100644 --- a/src/JsonSchema/Constraints/Drafts/Draft2019/NotConstraint.php +++ b/src/JsonSchema/Constraints/Drafts/Draft2019/NotConstraint.php @@ -28,8 +28,16 @@ public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = n return; } - $schemaConstraint = $this->factory->createInstanceFor('schema'); - $schemaConstraint->check($value, $schema->not, $path, $i); + // Only the validity of the subschema is needed, its errors are never reported + $previousFailFast = $this->factory->startFailFast(); + try { + $schemaConstraint = $this->factory->createInstanceFor('schema'); + $schemaConstraint->check($value, $schema->not, $path, $i); + } finally { + if ($previousFailFast !== null) { + $this->factory->stopFailFast($previousFailFast); + } + } if (!$schemaConstraint->isValid()) { return; diff --git a/src/JsonSchema/Constraints/Drafts/Draft2019/OneOfConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft2019/OneOfConstraint.php index fd93cefe..cac5a273 100644 --- a/src/JsonSchema/Constraints/Drafts/Draft2019/OneOfConstraint.php +++ b/src/JsonSchema/Constraints/Drafts/Draft2019/OneOfConstraint.php @@ -28,6 +28,35 @@ public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = n return; } + // Only the validity of each branch is needed to know whether exactly one of them matches. The errors of + // the branches are collected afterwards, by evaluating them once more, only if the oneOf fails. + $previousFailFast = $this->factory->startFailFast(); + if ($previousFailFast !== null) { + $matchedSchema = 0; + try { + foreach ($schema->oneOf as $oneOfSchema) { + $schemaConstraint = $this->factory->createInstanceFor('schema'); + $schemaConstraint->check($value, $oneOfSchema, $path, $i); + if ($schemaConstraint->isValid()) { + $matchedSchema++; + } + } + } finally { + $this->factory->stopFailFast($previousFailFast); + } + + if ($matchedSchema === 1) { + return; + } + + if ($previousFailFast) { + // Only the validity of this oneOf is needed as well + $this->addError(ConstraintError::ONE_OF(), $path); + + return; + } + } + $matchedSchema = 0; foreach ($schema->oneOf as $oneOfSchema) { $schemaConstraint = $this->factory->createInstanceFor('schema'); diff --git a/src/JsonSchema/Constraints/Drafts/Draft2019/PropertiesConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft2019/PropertiesConstraint.php index 4052b1b9..01811068 100644 --- a/src/JsonSchema/Constraints/Drafts/Draft2019/PropertiesConstraint.php +++ b/src/JsonSchema/Constraints/Drafts/Draft2019/PropertiesConstraint.php @@ -46,6 +46,9 @@ public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = n } $this->addErrors($schemaConstraint->getErrors()); + if ($this->factory->isFailFast()) { + return; + } } } } diff --git a/src/JsonSchema/Constraints/EvaluationState.php b/src/JsonSchema/Constraints/EvaluationState.php new file mode 100644 index 00000000..f7268716 --- /dev/null +++ b/src/JsonSchema/Constraints/EvaluationState.php @@ -0,0 +1,21 @@ + $checkMode */ @@ -147,6 +152,66 @@ public function getConfig(?int $options = null): int return $this->checkMode & $options; } + /** + * @internal + */ + public function getEvaluationState(): EvaluationState + { + if ($this->evaluationState === null) { + $this->evaluationState = new EvaluationState(); + } + + return $this->evaluationState; + } + + /** + * Shares the evaluation state of another factory, so that nested factories take part in the same evaluation + * + * @internal + */ + public function setEvaluationState(EvaluationState $evaluationState): void + { + $this->evaluationState = $evaluationState; + } + + /** + * Whether a constraint may stop at its first error, because only the validity of the value is needed + * + * @internal + */ + public function isFailFast(): bool + { + return $this->getEvaluationState()->failFast; + } + + /** + * Lets the constraints evaluating a subschema stop at its first error, when only its validity is needed. + * Returns the previous state, to be passed to stopFailFast(), or null if the check mode needs every + * constraint to be evaluated, because it modifies the value or throws on the first error. + * + * @internal + */ + public function startFailFast(): ?bool + { + if ($this->getConfig(Constraint::CHECK_MODE_APPLY_DEFAULTS | Constraint::CHECK_MODE_COERCE_TYPES | Constraint::CHECK_MODE_EXCEPTIONS)) { + return null; + } + + $evaluationState = $this->getEvaluationState(); + $previous = $evaluationState->failFast; + $evaluationState->failFast = true; + + return $previous; + } + + /** + * @internal + */ + public function stopFailFast(bool $previous): void + { + $this->getEvaluationState()->failFast = $previous; + } + public function getUriRetriever(): UriRetrieverInterface { return $this->uriRetriever; diff --git a/src/JsonSchema/Validator.php b/src/JsonSchema/Validator.php index b90f17aa..40735ff7 100644 --- a/src/JsonSchema/Validator.php +++ b/src/JsonSchema/Validator.php @@ -89,7 +89,18 @@ public function validate(&$value, $schema = null, ?int $checkMode = null): int ); } - $validator->check($value, $schema); + // Stop at the first error when only the validity of the value is needed + $evaluationState = $this->factory->getEvaluationState(); + $previousFailFast = $evaluationState->failFast; + if ($this->factory->getConfig(Constraint::CHECK_MODE_FAIL_FAST)) { + $evaluationState->failFast = true; + } + + try { + $validator->check($value, $schema); + } finally { + $evaluationState->failFast = $previousFailFast; + } $this->factory->setConfig($initialCheckMode); diff --git a/tests/Constraints/FailFastTest.php b/tests/Constraints/FailFastTest.php new file mode 100644 index 00000000..7b77eb46 --- /dev/null +++ b/tests/Constraints/FailFastTest.php @@ -0,0 +1,135 @@ + $expectedErrors pointer and constraint name of each error + */ + public function testAllErrorsAreReportedByDefault(string $dialect, string $schema, string $data, array $expectedErrors): void + { + $errors = $this->validate($dialect, $schema, $data, Constraint::CHECK_MODE_STRICT); + + self::assertSame($expectedErrors, $errors); + } + + /** + * @dataProvider provideCases + * + * @param list $expectedErrors + */ + public function testFailFastReportsOnlyTheFirstError(string $dialect, string $schema, string $data, array $expectedErrors): void + { + $errors = $this->validate($dialect, $schema, $data, Constraint::CHECK_MODE_STRICT | Constraint::CHECK_MODE_FAIL_FAST); + + self::assertCount(1, $errors); + } + + /** + * @dataProvider provideDialects + */ + public function testFailFastReportsNoErrorForAValidValue(string $dialect): void + { + $schema = '{"properties": {"p": {"oneOf": [{"type": "integer"}, {"items": {"anyOf": [{"type": "string"}, {"type": "boolean"}]}}]}}}'; + + $errors = $this->validate($dialect, $schema, '{"p": ["x", true]}', Constraint::CHECK_MODE_STRICT | Constraint::CHECK_MODE_FAIL_FAST); + + self::assertSame([], $errors); + } + + /** + * @return \Generator}> + */ + public static function provideCases(): \Generator + { + $cases = [ + 'oneOf without a match' => [ + '{"oneOf": [{"type": "string"}, {"properties": {"a": {"type": "integer"}, "b": {"type": "integer"}}}]}', + '{"a": "x", "b": "y"}', + [['', 'type'], ['/a', 'type'], ['/b', 'type'], ['', 'oneOf']], + ], + 'oneOf with two matches' => [ + '{"oneOf": [{"type": "object"}, {"properties": {"a": {"type": "string"}}}]}', + '{"a": "x"}', + [['', 'oneOf']], + ], + 'anyOf without a match' => [ + '{"anyOf": [{"type": "string"}, {"items": {"type": "integer"}}]}', + '["x", "y"]', + [['', 'type'], ['/0', 'type'], ['/1', 'type'], ['', 'anyOf']], + ], + 'not' => [ + '{"not": {"properties": {"a": {"type": "integer"}, "b": {"type": "integer"}}}}', + '{"a": 1, "b": 2}', + [['', 'not']], + ], + 'nested oneOf' => [ + '{"properties": {"p": {"oneOf": [{"type": "integer"}, {"items": {"oneOf": [{"type": "string"}, {"type": "boolean"}]}}]}}}', + '{"p": [1, "x", 2]}', + [ + ['/p', 'type'], + ['/p/0', 'type'], ['/p/0', 'type'], ['/p/0', 'oneOf'], + ['/p/2', 'type'], ['/p/2', 'type'], ['/p/2', 'oneOf'], + ['/p', 'oneOf'], + ], + ], + ]; + + foreach (self::provideDialects() as $dialectName => [$dialect]) { + foreach ($cases as $caseName => [$schema, $data, $expectedErrors]) { + yield $dialectName . ': ' . $caseName => [$dialect, $schema, $data, $expectedErrors]; + } + } + + foreach (['Draft-07' => DraftIdentifiers::DRAFT_7, 'Draft 2019-09' => DraftIdentifiers::DRAFT_2019_09] as $dialectName => $dialect) { + yield $dialectName . ': if' => [ + $dialect, + '{"if": {"properties": {"a": {"type": "integer"}, "b": {"type": "integer"}}}, "then": {"required": ["c"]}, "else": {"required": ["d"]}}', + '{"a": "x", "b": "y"}', + [['/d', 'required']], + ]; + } + } + + /** + * @return array + */ + public static function provideDialects(): array + { + return [ + 'Draft-06' => [DraftIdentifiers::DRAFT_6], + 'Draft-07' => [DraftIdentifiers::DRAFT_7], + 'Draft 2019-09' => [DraftIdentifiers::DRAFT_2019_09], + ]; + } + + /** + * @return list + */ + private function validate(string $dialect, string $schema, string $data, int $checkMode): array + { + $decodedSchema = json_decode($schema); + $decodedSchema->{'$schema'} = $dialect; + $decodedData = json_decode($data); + + $validator = new Validator(); + $validator->validate($decodedData, $decodedSchema, $checkMode); + + return array_map(static function (array $error): array { + return [$error['pointer'], $error['constraint']['name']]; + }, $validator->getErrors()); + } +}