Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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);
Expand Down
38 changes: 38 additions & 0 deletions src/JsonSchema/Constraints/Drafts/Draft2019/DynamicScope.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

declare(strict_types=1);

namespace JsonSchema\Constraints\Drafts\Draft2019;

/**
* The schema resources entered during the evaluation, which $recursiveRef uses to find its
* dynamic destination.
*/
class DynamicScope
{
/** @var list<object> */
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<object> the entered schema resources, the innermost first
*/
public function getResources(): array
{
return array_reverse($this->resources);
}
}
51 changes: 51 additions & 0 deletions src/JsonSchema/Constraints/Drafts/Draft2019/Factory.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<?php

declare(strict_types=1);

namespace JsonSchema\Constraints\Drafts\Draft2019;

use JsonSchema\Constraints\ConstraintInterface;
use JsonSchema\Entity\ErrorBagProxy;
use JsonSchema\Entity\JsonPointer;

class RecursiveRefConstraint implements ConstraintInterface
{
use ErrorBagProxy;

/** @var Factory */
private $factory;

public function __construct(?Factory $factory = null)
{
$this->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());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions src/JsonSchema/SchemaStorage.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down
89 changes: 89 additions & 0 deletions tests/Constraints/Drafts/Draft2019/RecursiveRefTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
<?php

declare(strict_types=1);

namespace JsonSchema\Tests\Constraints\Drafts\Draft2019;

use JsonSchema\Constraints\Constraint;
use JsonSchema\DraftIdentifiers;
use JsonSchema\Tests\Constraints\BaseTestCase;

class RecursiveRefTest extends BaseTestCase
{
protected $schemaSpec = DraftIdentifiers::DRAFT_2019_09;

public function getInvalidTests(): \Generator
{
yield 'without $recursiveAnchor it works like $ref' => [
'{"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":"#"}}
}
}
}
}';
}
}
13 changes: 0 additions & 13 deletions tests/JsonSchemaTestSuiteTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down