Skip to content

Commit 15df8fb

Browse files
committed
Default to draft-04 if $schema is undefined
Previous behavior was to throw a RuntimeException.
1 parent 298570e commit 15df8fb

File tree

2 files changed

+20
-10
lines changed

2 files changed

+20
-10
lines changed

src/JsonSchema/Constraints/SchemaConstraint.php

+8-4
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,8 @@
2323
*/
2424
class SchemaConstraint extends Constraint
2525
{
26+
const DEFAULT_SCHEMA_SPEC = 'http://json-schema.org/draft-04/schema#';
27+
2628
/**
2729
* {@inheritdoc}
2830
*/
@@ -42,13 +44,16 @@ public function check(&$element, $schema = null, JsonPointer $path = null, $i =
4244
throw new InvalidArgumentException('no schema found to verify against');
4345
}
4446

45-
// validate schema against whatever is defined in $validationSchema->$schema
47+
// validate schema against whatever is defined in $validationSchema->$schema. If no
48+
// schema is defined, assume self::DEFAULT_SCHEMA_SPEC (currently draft-04).
4649
if ($this->factory->getConfig(self::CHECK_MODE_VALIDATE_SCHEMA)) {
4750
if (!$this->getTypeCheck()->isObject($validationSchema)) {
4851
throw new RuntimeException('cannot validate non-object schema');
4952
}
50-
if (!$this->getTypeCheck()->propertyExists($validationSchema, '$schema')) {
51-
throw new RuntimeException('$schema is not set');
53+
if ($this->getTypeCheck()->propertyExists($validationSchema, '$schema')) {
54+
$schemaSpec = $this->getTypeCheck()->propertyGet($validationSchema, '$schema');
55+
} else {
56+
$schemaSpec = self::DEFAULT_SCHEMA_SPEC;
5257
}
5358

5459
// preload standard schema specs
@@ -58,7 +63,6 @@ public function check(&$element, $schema = null, JsonPointer $path = null, $i =
5863
'http://json-schema.org/draft-04/schema' => 'json-schema-draft-04.json',
5964
'http://json-schema.org/draft-04/schema#' => 'json-schema-draft-04.json'
6065
);
61-
$schemaSpec = $this->getTypeCheck()->propertyGet($validationSchema, '$schema');
6266
$schemaStorage = $this->factory->getSchemaStorage();
6367
foreach ($preload as $schemaID => $schemaFile) {
6468
$schemaStorage->addSchema(

tests/Constraints/SchemaValidationTest.php

+12-6
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,18 @@ public function getValidTests()
4949
}
5050
}',
5151
''
52+
),
53+
array( // inline schema with default (undefined) spec
54+
'{
55+
"$schema": {
56+
"properties": {
57+
"propertyOne": {
58+
"type": "string"
59+
}
60+
}
61+
}
62+
}',
63+
''
5264
)
5365
);
5466
}
@@ -64,10 +76,4 @@ public function testNonObjectSchema()
6476
$this->setExpectedException('JsonSchema\Exception\RuntimeException');
6577
parent::testValidCases('{"$schema": "notAnObject"}', '');
6678
}
67-
68-
public function testMissingSchemaSpec()
69-
{
70-
$this->setExpectedException('JsonSchema\Exception\RuntimeException');
71-
parent::testValidCases('{"$schema":{}}', '');
72-
}
7379
}

0 commit comments

Comments
 (0)