Debian Codegraph @

src/keywords/content.rs

raw symbols SCIP
1 //! Validators for `contentMediaType` and `contentEncoding` keywords.
2 use crate::{
3 compiler,
4 content_encoding::{ContentEncodingCheckType, ContentEncodingConverterType},
5 content_media_type::ContentMediaTypeCheckType,
6 error::ValidationError,
7 keywords::CompilationResult,
8 paths::{LazyLocation, Location},
9 types::JsonType,
10 validator::{Validate, ValidationContext},
11 };
12 use serde_json::{Map, Value};
13
14 /// Validator for `contentMediaType` keyword.
15 pub(crate) struct ContentMediaTypeValidator {
16 media_type: String,
17 func: ContentMediaTypeCheckType,
18 location: Location,
19 }
20
21 impl ContentMediaTypeValidator {
22 #[inline]
23 pub(crate) fn compile(
24 media_type: &str,
25 func: ContentMediaTypeCheckType,
26 location: Location,
27 ) -> CompilationResult<'_> {
28 Ok(Box::new(ContentMediaTypeValidator {
29 media_type: media_type.to_string(),
30 func,
31 location,
32 }))
33 }
34 }
35
36 /// Validator delegates validation to the stored function.
37 impl Validate for ContentMediaTypeValidator {
38 fn is_valid(&self, instance: &Value, _ctx: &mut ValidationContext) -> bool {
39 if let Value::String(item) = instance {
40 (self.func)(item)
41 } else {
42 true
43 }
44 }
45
46 fn validate<'i>(
47 &self,
48 instance: &'i Value,
49 location: &LazyLocation,
50 ctx: &mut ValidationContext,
51 ) -> Result<(), ValidationError<'i>> {
52 if self.is_valid(instance, ctx) {
53 Ok(())
54 } else if let Value::String(_) = instance {
55 Err(ValidationError::content_media_type(
56 self.location.clone(),
57 location.into(),
58 instance,
59 &self.media_type,
60 ))
61 } else {
62 Ok(())
63 }
64 }
65 }
66
67 /// Validator for `contentEncoding` keyword.
68 pub(crate) struct ContentEncodingValidator {
69 encoding: String,
70 func: ContentEncodingCheckType,
71 location: Location,
72 }
73
74 impl ContentEncodingValidator {
75 #[inline]
76 pub(crate) fn compile(
77 encoding: &str,
78 func: ContentEncodingCheckType,
79 location: Location,
80 ) -> CompilationResult<'_> {
81 Ok(Box::new(ContentEncodingValidator {
82 encoding: encoding.to_string(),
83 func,
84 location,
85 }))
86 }
87 }
88
89 impl Validate for ContentEncodingValidator {
90 fn is_valid(&self, instance: &Value, _ctx: &mut ValidationContext) -> bool {
91 if let Value::String(item) = instance {
92 (self.func)(item)
93 } else {
94 true
95 }
96 }
97
98 fn validate<'i>(
99 &self,
100 instance: &'i Value,
101 location: &LazyLocation,
102 ctx: &mut ValidationContext,
103 ) -> Result<(), ValidationError<'i>> {
104 if self.is_valid(instance, ctx) {
105 Ok(())
106 } else if let Value::String(_) = instance {
107 Err(ValidationError::content_encoding(
108 self.location.clone(),
109 location.into(),
110 instance,
111 &self.encoding,
112 ))
113 } else {
114 Ok(())
115 }
116 }
117 }
118
119 /// Combined validator for both `contentEncoding` and `contentMediaType` keywords.
120 pub(crate) struct ContentMediaTypeAndEncodingValidator {
121 media_type: String,
122 encoding: String,
123 func: ContentMediaTypeCheckType,
124 converter: ContentEncodingConverterType,
125 location: Location,
126 }
127
128 impl ContentMediaTypeAndEncodingValidator {
129 #[inline]
130 pub(crate) fn compile<'a>(
131 media_type: &'a str,
132 encoding: &'a str,
133 func: ContentMediaTypeCheckType,
134 converter: ContentEncodingConverterType,
135 location: Location,
136 ) -> CompilationResult<'a> {
137 Ok(Box::new(ContentMediaTypeAndEncodingValidator {
138 media_type: media_type.to_string(),
139 encoding: encoding.to_string(),
140 func,
141 converter,
142 location,
143 }))
144 }
145 }
146
147 /// Decode the input value & check media type
148 impl Validate for ContentMediaTypeAndEncodingValidator {
149 fn is_valid(&self, instance: &Value, _ctx: &mut ValidationContext) -> bool {
150 if let Value::String(item) = instance {
151 match (self.converter)(item) {
152 Ok(None) | Err(_) => false,
153 Ok(Some(converted)) => (self.func)(&converted),
154 }
155 } else {
156 true
157 }
158 }
159
160 fn validate<'i>(
161 &self,
162 instance: &'i Value,
163 location: &LazyLocation,
164 _ctx: &mut ValidationContext,
165 ) -> Result<(), ValidationError<'i>> {
166 if let Value::String(item) = instance {
167 match (self.converter)(item) {
168 Ok(None) => Err(ValidationError::content_encoding(
169 self.location.join("contentEncoding"),
170 location.into(),
171 instance,
172 &self.encoding,
173 )),
174 Ok(Some(converted)) => {
175 if (self.func)(&converted) {
176 Ok(())
177 } else {
178 Err(ValidationError::content_media_type(
179 self.location.join("contentMediaType"),
180 location.into(),
181 instance,
182 &self.media_type,
183 ))
184 }
185 }
186 Err(e) => Err(e),
187 }
188 } else {
189 Ok(())
190 }
191 }
192 }
193
194 #[inline]
195 pub(crate) fn compile_media_type<'a>(
196 ctx: &compiler::Context,
197 schema: &'a Map<String, Value>,
198 subschema: &'a Value,
199 ) -> Option<CompilationResult<'a>> {
200 match subschema {
201 Value::String(media_type) => {
202 let func = ctx.get_content_media_type_check(media_type.as_str())?;
203 if let Some(content_encoding) = schema.get("contentEncoding") {
204 match content_encoding {
205 Value::String(content_encoding) => {
206 let converter = ctx.get_content_encoding_convert(content_encoding)?;
207 Some(ContentMediaTypeAndEncodingValidator::compile(
208 media_type,
209 content_encoding,
210 func,
211 converter,
212 ctx.location().clone(),
213 ))
214 }
215 _ => Some(Err(ValidationError::single_type_error(
216 Location::new(),
217 ctx.location().clone(),
218 content_encoding,
219 JsonType::String,
220 ))),
221 }
222 } else {
223 Some(ContentMediaTypeValidator::compile(
224 media_type,
225 func,
226 ctx.location().join("contentMediaType"),
227 ))
228 }
229 }
230 _ => Some(Err(ValidationError::single_type_error(
231 Location::new(),
232 ctx.location().clone(),
233 subschema,
234 JsonType::String,
235 ))),
236 }
237 }
238
239 #[inline]
240 pub(crate) fn compile_content_encoding<'a>(
241 ctx: &compiler::Context,
242 schema: &'a Map<String, Value>,
243 subschema: &'a Value,
244 ) -> Option<CompilationResult<'a>> {
245 // Performed during media type validation
246 if schema.get("contentMediaType").is_some() {
247 // TODO. what if media type is not supported?
248 return None;
249 }
250 match subschema {
251 Value::String(content_encoding) => {
252 let func = ctx.get_content_encoding_check(content_encoding)?;
253 Some(ContentEncodingValidator::compile(
254 content_encoding,
255 func,
256 ctx.location().join("contentEncoding"),
257 ))
258 }
259 _ => Some(Err(ValidationError::single_type_error(
260 Location::new(),
261 ctx.location().clone(),
262 subschema,
263 JsonType::String,
264 ))),
265 }
266 }
267
268 #[cfg(test)]
269 mod tests {
270 use referencing::Draft;
271 use serde_json::{json, Value};
272 use test_case::test_case;
273
274 #[test_case(&json!({"contentEncoding": "base64"}), &json!("asd"), "/contentEncoding")]
275 #[test_case(&json!({"contentMediaType": "application/json"}), &json!("asd"), "/contentMediaType")]
276 #[test_case(&json!({"contentMediaType": "application/json", "contentEncoding": "base64"}), &json!("ezp9Cg=="), "/contentMediaType")]
277 #[test_case(&json!({"contentMediaType": "application/json", "contentEncoding": "base64"}), &json!("{}"), "/contentEncoding")]
278 fn location(schema: &Value, instance: &Value, expected: &str) {
279 let validator = crate::options()
280 .with_draft(Draft::Draft7)
281 .build(schema)
282 .expect("Invalid schema");
283 let error = validator.validate(instance).expect_err("Should fail");
284 assert_eq!(error.schema_path().as_str(), expected);
285 }
286 }