diff --git a/src/JsonSchema/Constraints/Drafts/Draft2019/Draft2019Constraint.php b/src/JsonSchema/Constraints/Drafts/Draft2019/Draft2019Constraint.php index b5cbc10a..f7e6c35b 100644 --- a/src/JsonSchema/Constraints/Drafts/Draft2019/Draft2019Constraint.php +++ b/src/JsonSchema/Constraints/Drafts/Draft2019/Draft2019Constraint.php @@ -15,13 +15,22 @@ class Draft2019Constraint extends Constraint { + /** @var Factory */ + protected $factory; + 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 instanceof Factory) { + // Nested schemas share the dynamic scope of the evaluation they are part of + $draftFactory->setDynamicScope($factory->getDynamicScope()); + } + + parent::__construct($draftFactory); } public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void @@ -47,8 +56,33 @@ public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = n return; } + // The evaluation enters a new schema resource at the root schema and at each $id + $dynamicScope = $this->factory->getDynamicScope(); + $entersResource = is_object($schema) + && ($dynamicScope->isEmpty() || (property_exists($schema, '$id') && is_string($schema->{'$id'}))); + if ($entersResource) { + $dynamicScope->enter($schema); + } + + try { + $this->checkKeywords($value, $schema, $path, $i); + } finally { + if ($entersResource) { + $dynamicScope->leave(); + } + } + } + + /** + * @param mixed $value + * @param mixed $schema + * @param mixed $i + */ + private function checkKeywords(&$value, $schema, ?JsonPointer $path, $i): void + { // Apply defaults $this->checkForKeyword('ref', $value, $schema, $path, $i); + $this->checkForKeyword('recursiveRef', $value, $schema, $path, $i); $this->checkForKeyword('required', $value, $schema, $path, $i); $this->checkForKeyword('contains', $value, $schema, $path, $i); $this->checkForKeyword('properties', $value, $schema, $path, $i); diff --git a/src/JsonSchema/Constraints/Drafts/Draft2019/DynamicScope.php b/src/JsonSchema/Constraints/Drafts/Draft2019/DynamicScope.php new file mode 100644 index 00000000..263689bf --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft2019/DynamicScope.php @@ -0,0 +1,38 @@ + */ + private $resources = []; + + public function enter(object $resource): void + { + $this->resources[] = $resource; + } + + public function leave(): void + { + array_pop($this->resources); + } + + public function isEmpty(): bool + { + return $this->resources === []; + } + + /** + * @return list the entered schema resources, the innermost first + */ + public function getResources(): array + { + return array_reverse($this->resources); + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft2019/Factory.php b/src/JsonSchema/Constraints/Drafts/Draft2019/Factory.php index cbe2c539..33faaad1 100644 --- a/src/JsonSchema/Constraints/Drafts/Draft2019/Factory.php +++ b/src/JsonSchema/Constraints/Drafts/Draft2019/Factory.php @@ -47,6 +47,57 @@ class Factory extends \JsonSchema\Constraints\Factory 'properties' => PropertiesConstraint::class, 'items' => ItemsConstraint::class, 'ref' => RefConstraint::class, + 'recursiveRef' => RecursiveRefConstraint::class, 'content' => ContentConstraint::class, ]; + + /** @var DynamicScope|null */ + private $dynamicScope; + + public function getDynamicScope(): DynamicScope + { + if ($this->dynamicScope === null) { + $this->dynamicScope = new DynamicScope(); + } + + return $this->dynamicScope; + } + + public function setDynamicScope(DynamicScope $dynamicScope): void + { + $this->dynamicScope = $dynamicScope; + } + + /** + * Resolve a $recursiveRef. Its initial target is resolved like a $ref, and when that target + * declares "$recursiveAnchor": true, the outermost schema resource of the dynamic scope + * reachable through resources that declare it as well is used instead. + * + * @return mixed + */ + public function resolveRecursiveRef(string $reference) + { + $refSchema = $this->getSchemaStorage()->resolveRef($reference); + if (!$this->hasRecursiveAnchor($refSchema)) { + return $refSchema; + } + + foreach ($this->getDynamicScope()->getResources() as $resource) { + if (!$this->hasRecursiveAnchor($resource)) { + break; + } + + $refSchema = $resource; + } + + return $refSchema; + } + + /** + * @param mixed $schema + */ + private function hasRecursiveAnchor($schema): bool + { + return is_object($schema) && property_exists($schema, '$recursiveAnchor') && $schema->{'$recursiveAnchor'} === true; + } } diff --git a/src/JsonSchema/Constraints/Drafts/Draft2019/RecursiveRefConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft2019/RecursiveRefConstraint.php new file mode 100644 index 00000000..821f36dc --- /dev/null +++ b/src/JsonSchema/Constraints/Drafts/Draft2019/RecursiveRefConstraint.php @@ -0,0 +1,45 @@ +factory = $factory ?: new Factory(); + $this->initialiseErrorBag($this->factory); + } + + public function check(&$value, $schema = null, ?JsonPointer $path = null, $i = null): void + { + if (!is_object($schema) || !property_exists($schema, '$recursiveRef') || !is_string($schema->{'$recursiveRef'})) { + return; + } + + try { + $refSchema = $this->factory->resolveRecursiveRef($schema->{'$recursiveRef'}); + } catch (\Exception $e) { + return; + } + + $schemaConstraint = $this->factory->createInstanceFor('schema'); + $schemaConstraint->check($value, $refSchema, $path, $i); + + if ($schemaConstraint->isValid()) { + return; + } + + $this->addErrors($schemaConstraint->getErrors()); + } +} diff --git a/src/JsonSchema/Constraints/Drafts/Draft2019/UnevaluatedPropertiesConstraint.php b/src/JsonSchema/Constraints/Drafts/Draft2019/UnevaluatedPropertiesConstraint.php index 77ecbcec..017ee65c 100644 --- a/src/JsonSchema/Constraints/Drafts/Draft2019/UnevaluatedPropertiesConstraint.php +++ b/src/JsonSchema/Constraints/Drafts/Draft2019/UnevaluatedPropertiesConstraint.php @@ -90,6 +90,24 @@ private function collectEvaluatedProperties(object $schema, object $value, ?Json } } + if (property_exists($schema, '$recursiveRef') && is_string($schema->{'$recursiveRef'})) { + $reference = '$recursiveRef:' . $schema->{'$recursiveRef'}; + if (!in_array($reference, $visitedRefs, true)) { + try { + $visitedRefs[] = $reference; + $resolvedSchema = $this->factory->resolveRecursiveRef($schema->{'$recursiveRef'}); + if (is_object($resolvedSchema)) { + $evaluated = array_merge( + $evaluated, + $this->collectEvaluatedProperties($resolvedSchema, $value, $path, $visitedRefs) + ); + } + } catch (\Exception $e) { + // Let the normal reference validation report resolution errors. + } + } + } + $properties = get_object_vars($value); // A nested unevaluatedProperties applies to every property its subschema has not evaluated otherwise, so diff --git a/src/JsonSchema/SchemaStorage.php b/src/JsonSchema/SchemaStorage.php index 9e794431..28733960 100644 --- a/src/JsonSchema/SchemaStorage.php +++ b/src/JsonSchema/SchemaStorage.php @@ -144,6 +144,17 @@ private function expandRefs(&$schema, ?string $parentId = null, array $propertyS $schema->{'$ref'} = $ref; } + if (property_exists($schema, '$recursiveRef') && is_string($schema->{'$recursiveRef'})) { + // The initial target of $recursiveRef is resolved against the id of its own schema + $baseId = $parentId; + $schemaId = $this->findSchemaIdInObject($schema); + if (is_string($schemaId)) { + $baseId = $this->uriResolver->resolve($schemaId, $parentId); + } + $refPointer = new JsonPointer($this->uriResolver->resolve($schema->{'$recursiveRef'}, $baseId)); + $schema->{'$recursiveRef'} = (string) $refPointer; + } + $parentProperty = array_slice($propertyStack, -1)[0] ?? ''; foreach ($schema as $propertyName => &$member) { if ( diff --git a/tests/Constraints/Drafts/Draft2019/RecursiveRefTest.php b/tests/Constraints/Drafts/Draft2019/RecursiveRefTest.php new file mode 100644 index 00000000..e0042f48 --- /dev/null +++ b/tests/Constraints/Drafts/Draft2019/RecursiveRefTest.php @@ -0,0 +1,89 @@ + [ + '{"foo":{"bar":false}}', + '{ + "$schema":"' . DraftIdentifiers::DRAFT_2019_09 . '", + "properties":{"foo":{"$recursiveRef":"#"}}, + "additionalProperties":false + }', + Constraint::CHECK_MODE_STRICT, + ]; + + yield 'recursion uses the outermost schema with $recursiveAnchor' => [ + '{"name":"root","children":[{"children":[]}]}', + $this->getExtendedTreeSchema(true, true), + Constraint::CHECK_MODE_STRICT, + ]; + } + + public function getValidTests(): \Generator + { + yield 'without $recursiveAnchor it works like $ref' => [ + '{"foo":{"foo":false}}', + '{ + "$schema":"' . DraftIdentifiers::DRAFT_2019_09 . '", + "properties":{"foo":{"$recursiveRef":"#"}}, + "additionalProperties":false + }', + Constraint::CHECK_MODE_STRICT, + ]; + + yield 'recursion uses the outermost schema with $recursiveAnchor' => [ + '{"name":"root","children":[{"name":"child","children":[]}]}', + $this->getExtendedTreeSchema(true, true), + Constraint::CHECK_MODE_STRICT, + ]; + + yield 'recursion stays in the initial target without $recursiveAnchor' => [ + '{"name":"root","children":[{"children":[]}]}', + $this->getExtendedTreeSchema(true, false), + Constraint::CHECK_MODE_STRICT, + ]; + + yield 'recursion stays in the initial target when the outer schema has no $recursiveAnchor' => [ + '{"name":"root","children":[{"children":[]}]}', + $this->getExtendedTreeSchema(false, true), + Constraint::CHECK_MODE_STRICT, + ]; + } + + /** + * A tree whose children are evaluated through $recursiveRef, extended by an outer schema + * which requires a name. + */ + private function getExtendedTreeSchema(bool $outerAnchor, bool $treeAnchor): string + { + return '{ + "$schema":"' . DraftIdentifiers::DRAFT_2019_09 . '", + "$id":"http://example.com/recursive-ref/strict-tree.json", + "$recursiveAnchor":' . json_encode($outerAnchor) . ', + "allOf":[{"$ref":"tree.json"}], + "required":["name"], + "$defs":{ + "tree":{ + "$id":"tree.json", + "$recursiveAnchor":' . json_encode($treeAnchor) . ', + "type":"object", + "properties":{ + "children":{"type":"array","items":{"$recursiveRef":"#"}} + } + } + } + }'; + } +} diff --git a/tests/JsonSchemaTestSuiteTest.php b/tests/JsonSchemaTestSuiteTest.php index 204cbd99..64de7b2d 100644 --- a/tests/JsonSchemaTestSuiteTest.php +++ b/tests/JsonSchemaTestSuiteTest.php @@ -126,24 +126,11 @@ private function shouldNotYieldTest(string $name): bool { $skip = [ // Draft 2019-09 complex constraints, which aren't supported initially - '[draft2019-09/recursiveRef.json]: $recursiveRef without $recursiveAnchor works like $ref: recursive mismatch is expected to be invalid', - '[draft2019-09/recursiveRef.json]: $recursiveRef without using nesting: integer does not match as a property value is expected to be invalid', - '[draft2019-09/recursiveRef.json]: $recursiveRef without using nesting: two levels, no match is expected to be invalid', - '[draft2019-09/recursiveRef.json]: $recursiveRef with $recursiveAnchor: false works like $ref: integer does not match as a property value is expected to be invalid', - '[draft2019-09/recursiveRef.json]: $recursiveRef with $recursiveAnchor: false works like $ref: two levels, integer does not match as a property value is expected to be invalid', - '[draft2019-09/recursiveRef.json]: $recursiveRef with no $recursiveAnchor works like $ref: integer does not match as a property value is expected to be invalid', - '[draft2019-09/recursiveRef.json]: $recursiveRef with no $recursiveAnchor works like $ref: two levels, integer does not match as a property value is expected to be invalid', - '[draft2019-09/recursiveRef.json]: $recursiveRef with no $recursiveAnchor in the outer schema resource: leaf node does not match: recursion only uses inner schema is expected to be invalid', - '[draft2019-09/recursiveRef.json]: $recursiveRef with no $recursiveAnchor in the initial target schema resource: leaf node does not match: recursion uses the inner schema is expected to be invalid', - '[draft2019-09/recursiveRef.json]: multiple dynamic paths to the $recursiveRef keyword: recurse to integerNode - floats are not allowed is expected to be invalid', - '[draft2019-09/recursiveRef.json]: dynamic $recursiveRef destination (not predictable at schema compile time): integer node is expected to be invalid', '[draft2019-09/vocabulary.json]: schema that uses custom metaschema with with no validation vocabulary: applicator vocabulary still works is expected to be invalid', '[draft2019-09/vocabulary.json]: schema that uses custom metaschema with with no validation vocabulary: no validation: valid number is expected to be valid', '[draft2019-09/vocabulary.json]: schema that uses custom metaschema with with no validation vocabulary: no validation: invalid number, but it still validates is expected to be valid', '[draft2019-09/vocabulary.json]: ignore unrecognized optional vocabulary: string value is expected to be invalid', '[draft2019-09/vocabulary.json]: ignore unrecognized optional vocabulary: number value is expected to be valid', - '[draft2019-09/ref.json]: $ref with $recursiveAnchor: extra items disallowed for root is expected to be invalid', - '[draft2019-09/unevaluatedProperties.json]: unevaluatedProperties with $recursiveRef: with no unevaluated properties is expected to be valid', '[draft2019-09/unevaluatedItems.json]: unevaluatedItems with $recursiveRef: with no unevaluated items is expected to be valid', // Optional: Anchor, not yet implemented // Optional: bignum — PHP does not natively support arbitrary-precision integers/floats