Allow running visitors against pre-2020-12 schemas

This commit is contained in:
Graham Esau 2024-05-20 15:25:16 +01:00
parent 3aa0e7fa3c
commit d32231c082

View file

@ -45,6 +45,11 @@ pub trait Visitor {
pub fn visit_schema<V: Visitor + ?Sized>(v: &mut V, schema: &mut Schema) { pub fn visit_schema<V: Visitor + ?Sized>(v: &mut V, schema: &mut Schema) {
if let Some(obj) = schema.as_object_mut() { if let Some(obj) = schema.as_object_mut() {
for (key, value) in obj { for (key, value) in obj {
// This is intentionally written to work with multiple JSON Schema versions, so that
// users can add their own visitors on the end of e.g. `SchemaSettings::draft07()` and
// they will still apply to all subschemas "as expected".
// This is why this match statement contains both `additionalProperties` (which was
// dropped in draft 2020-12) and `prefixItems` (which was added in draft 2020-12).
match key.as_str() { match key.as_str() {
"not" "not"
| "if" | "if"
@ -53,7 +58,7 @@ pub fn visit_schema<V: Visitor + ?Sized>(v: &mut V, schema: &mut Schema) {
| "contains" | "contains"
| "additionalProperties" | "additionalProperties"
| "propertyNames" | "propertyNames"
| "items" => { | "additionalItems" => {
if let Ok(subschema) = value.try_into() { if let Ok(subschema) = value.try_into() {
v.visit_schema(subschema) v.visit_schema(subschema)
} }
@ -67,6 +72,18 @@ pub fn visit_schema<V: Visitor + ?Sized>(v: &mut V, schema: &mut Schema) {
} }
} }
} }
// Support `items` array even though this is not allowed in draft 2020-12 (see above comment)
"items" => {
if let Some(array) = value.as_array_mut() {
for value in array {
if let Ok(subschema) = value.try_into() {
v.visit_schema(subschema)
}
}
} else if let Ok(subschema) = value.try_into() {
v.visit_schema(subschema)
}
}
"properties" | "patternProperties" => { "properties" | "patternProperties" => {
if let Some(obj) = value.as_object_mut() { if let Some(obj) = value.as_object_mut() {
for value in obj.values_mut() { for value in obj.values_mut() {