json_model/attribute/
enum_values.rs

1use super::{AllowedType, Attribute};
2use crate::definition::Type;
3use crate::error::{Error, ValidationError};
4use crate::validator::{Context, DocumentPath, State};
5
6use std::collections::HashSet;
7
8use serde_json;
9
10#[derive(Debug)]
11pub struct EnumValues {
12    name: String,
13    values: Vec<serde_json::Value>,
14}
15
16impl EnumValues {
17    pub fn new(mut path: DocumentPath, ctx: &Context) -> Result<Self, Error> {
18        let obj = ctx.raw_definition();
19
20        match Type::new(obj, path.clone())? {
21            Type::Enum => (),
22            typ => return Err(Error::ForbiddenType { path, typ }),
23        };
24
25        let values = match obj.get(ctx.name().as_str()) {
26            Some(values) => match values.as_array() {
27                Some(values_arr) => values_arr,
28                None => {
29                    path.add(ctx.name().as_str());
30                    return Err(Error::InvalidValue {
31                        path,
32                        value: values.clone(),
33                    });
34                }
35            },
36            None => {
37                return Err(Error::MissingAttribute {
38                    path,
39                    attr: ctx.name(),
40                })
41            }
42        };
43
44        Ok(EnumValues {
45            name: ctx.name(),
46            values: values.clone(),
47        })
48    }
49
50    pub fn allowed_types() -> HashSet<AllowedType> {
51        let mut set = HashSet::<AllowedType>::new();
52        set.insert(AllowedType::new(Type::Enum, true));
53        set
54    }
55
56    pub fn build(
57        _: &mut State,
58        path: DocumentPath,
59        ctx: &Context,
60    ) -> Result<Box<Attribute>, Error> {
61        Ok(Box::new(EnumValues::new(path, ctx)?))
62    }
63}
64
65impl Attribute for EnumValues {
66    fn validate(
67        &self,
68        _: &State,
69        path: Vec<String>,
70        input: &serde_json::Value,
71    ) -> Result<(), ValidationError> {
72        for v in &self.values {
73            if v == input {
74                return Ok(());
75            }
76        }
77        return Err(ValidationError::Failure {
78            rule: "value".to_string(),
79            path: path,
80            message: "Value is invalid.".to_string(),
81        });
82    }
83}