Skip to content

Commit

Permalink
Default to draft-04 if $schema is undefined
Browse files Browse the repository at this point in the history
Previous behavior was to throw a RuntimeException.
  • Loading branch information
erayd committed Feb 22, 2017
1 parent 298570e commit 15df8fb
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 10 deletions.
12 changes: 8 additions & 4 deletions src/JsonSchema/Constraints/SchemaConstraint.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
*/
class SchemaConstraint extends Constraint
{
const DEFAULT_SCHEMA_SPEC = 'http://json-schema.org/draft-04/schema#';

/**
* {@inheritdoc}
*/
Expand All @@ -42,13 +44,16 @@ public function check(&$element, $schema = null, JsonPointer $path = null, $i =
throw new InvalidArgumentException('no schema found to verify against');
}

// validate schema against whatever is defined in $validationSchema->$schema
// validate schema against whatever is defined in $validationSchema->$schema. If no
// schema is defined, assume self::DEFAULT_SCHEMA_SPEC (currently draft-04).
if ($this->factory->getConfig(self::CHECK_MODE_VALIDATE_SCHEMA)) {
if (!$this->getTypeCheck()->isObject($validationSchema)) {
throw new RuntimeException('cannot validate non-object schema');
}
if (!$this->getTypeCheck()->propertyExists($validationSchema, '$schema')) {
throw new RuntimeException('$schema is not set');
if ($this->getTypeCheck()->propertyExists($validationSchema, '$schema')) {
$schemaSpec = $this->getTypeCheck()->propertyGet($validationSchema, '$schema');
} else {
$schemaSpec = self::DEFAULT_SCHEMA_SPEC;
}

// preload standard schema specs
Expand All @@ -58,7 +63,6 @@ public function check(&$element, $schema = null, JsonPointer $path = null, $i =
'http://json-schema.org/draft-04/schema' => 'json-schema-draft-04.json',
'http://json-schema.org/draft-04/schema#' => 'json-schema-draft-04.json'
);
$schemaSpec = $this->getTypeCheck()->propertyGet($validationSchema, '$schema');
$schemaStorage = $this->factory->getSchemaStorage();
foreach ($preload as $schemaID => $schemaFile) {
$schemaStorage->addSchema(
Expand Down
18 changes: 12 additions & 6 deletions tests/Constraints/SchemaValidationTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,18 @@ public function getValidTests()
}
}',
''
),
array( // inline schema with default (undefined) spec
'{
"$schema": {
"properties": {
"propertyOne": {
"type": "string"
}
}
}
}',
''
)
);
}
Expand All @@ -64,10 +76,4 @@ public function testNonObjectSchema()
$this->setExpectedException('JsonSchema\Exception\RuntimeException');
parent::testValidCases('{"$schema": "notAnObject"}', '');
}

public function testMissingSchemaSpec()
{
$this->setExpectedException('JsonSchema\Exception\RuntimeException');
parent::testValidCases('{"$schema":{}}', '');
}
}

0 comments on commit 15df8fb

Please sign in to comment.