1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
use crate::state::{
    language::Language,
    oca::{DynOverlay, OCABuilder, OCATranslation, OCA},
};
use std::collections::{HashMap, HashSet};

#[derive(Debug)]
pub enum Error {
    Custom(String),
    MissingTranslations(Language),
    MissingMetaTranslation(Language, String),
    UnexpectedTranslations(Language),
    MissingAttributeTranslation(Language, String),
}

pub struct Validator {
    enforced_translations: Vec<Language>,
}

impl Default for Validator {
    fn default() -> Self {
        Self::new()
    }
}

impl Validator {
    pub fn new() -> Validator {
        Validator {
            enforced_translations: vec![],
        }
    }

    pub fn enforce_translations(mut self, languages: Vec<Language>) -> Validator {
        self.enforced_translations = self
            .enforced_translations
            .into_iter()
            .chain(languages.into_iter())
            .collect::<Vec<Language>>();
        self
    }

    pub fn validate(self, oca: &OCA) -> Result<(), Vec<Error>> {
        let enforced_langs: HashSet<_> = self.enforced_translations.iter().collect();
        let mut errors: Vec<Error> = vec![];

        let oca_str = serde_json::to_string(&serde_json::value::to_value(oca).unwrap()).unwrap();
        let oca_builder: OCABuilder = serde_json::from_str(oca_str.as_str()).unwrap();

        if !oca_builder.meta_translations.is_empty() {
            if let Err(meta_errors) =
                self.validate_meta(&enforced_langs, &oca_builder.meta_translations)
            {
                errors = errors
                    .into_iter()
                    .chain(meta_errors.into_iter().map(|e| {
                        if let Error::UnexpectedTranslations(lang) = e {
                            Error::Custom(format!(
                                "meta overlay: translations in {:?} language are not enforced",
                                lang
                            ))
                        } else if let Error::MissingTranslations(lang) = e {
                            Error::Custom(format!(
                                "meta overlay: translations in {:?} language are missing",
                                lang
                            ))
                        } else if let Error::MissingMetaTranslation(lang, attr) = e {
                            Error::Custom(format!(
                                "meta overlay: for '{}' translation in {:?} language is missing",
                                attr, lang
                            ))
                        } else {
                            e
                        }
                    }))
                    .collect();
            }
        }

        for overlay_type in &["entry", "information", "label"] {
            let typed_overlays: Vec<_> = oca
                .overlays
                .iter()
                .filter(|x| {
                    x.overlay_type()
                        .contains(format!("/{}/", overlay_type).as_str())
                })
                .collect();
            if typed_overlays.is_empty() {
                continue;
            }

            if let Err(translation_errors) =
                self.validate_translations(&enforced_langs, typed_overlays)
            {
                errors = errors.into_iter().chain(
                    translation_errors.into_iter().map(|e| {
                        if let Error::UnexpectedTranslations(lang) = e {
                            Error::Custom(
                                format!("{} overlay: translations in {:?} language are not enforced", overlay_type, lang)
                            )
                        } else if let Error::MissingTranslations(lang) = e {
                            Error::Custom(
                                format!("{} overlay: translations in {:?} language are missing", overlay_type, lang)
                            )
                        } else if let Error::MissingAttributeTranslation(lang, attr_name) = e {
                            Error::Custom(
                                format!("{} overlay: for '{}' attribute missing translations in {:?} language", overlay_type, attr_name, lang)
                            )
                        } else {
                            e
                        }
                    })
                ).collect();
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    fn validate_meta(
        &self,
        enforced_langs: &HashSet<&Language>,
        translations: &HashMap<Language, OCATranslation>,
    ) -> Result<(), Vec<Error>> {
        let mut errors: Vec<Error> = vec![];
        let translation_langs: HashSet<_> = translations.keys().collect();

        let missing_enforcement: HashSet<&_> =
            translation_langs.difference(enforced_langs).collect();
        for m in missing_enforcement {
            errors.push(Error::UnexpectedTranslations(m.to_string()));
        }

        let missing_translations: HashSet<&_> =
            enforced_langs.difference(&translation_langs).collect();
        for m in missing_translations {
            errors.push(Error::MissingTranslations(m.to_string()));
        }

        let (name_defined, name_undefined): (Vec<_>, Vec<_>) =
            translations.iter().partition(|(_lang, t)| t.name.is_some());
        if !name_defined.is_empty() {
            let name_undefined_langs: HashSet<_> = name_undefined.iter().map(|x| x.0).collect();
            for m in name_undefined_langs {
                errors.push(Error::MissingMetaTranslation(
                    m.to_string(),
                    "name".to_string(),
                ));
            }
        }

        let (desc_defined, desc_undefined): (Vec<_>, Vec<_>) = translations
            .iter()
            .partition(|(_lang, t)| t.description.is_some());
        if !desc_defined.is_empty() {
            let desc_undefined_langs: HashSet<_> = desc_undefined.iter().map(|x| x.0).collect();
            for m in desc_undefined_langs {
                errors.push(Error::MissingMetaTranslation(
                    m.to_string(),
                    "description".to_string(),
                ));
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    fn validate_translations(
        &self,
        enforced_langs: &HashSet<&Language>,
        overlays: Vec<&DynOverlay>,
    ) -> Result<(), Vec<Error>> {
        let mut errors: Vec<Error> = vec![];

        let overlay_langs: HashSet<_> = overlays.iter().map(|x| x.language().unwrap()).collect();

        let missing_enforcement: HashSet<&_> = overlay_langs.difference(enforced_langs).collect();
        for m in missing_enforcement {
            errors.push(Error::UnexpectedTranslations(m.to_string()));
        }

        let missing_translations: HashSet<&_> = enforced_langs.difference(&overlay_langs).collect();
        for m in missing_translations {
            errors.push(Error::MissingTranslations(m.to_string()));
        }

        let all_attributes: HashSet<&String> =
            overlays.iter().flat_map(|o| o.attributes()).collect();
        for overlay in overlays.iter() {
            let attributes: HashSet<_> = overlay.attributes().into_iter().collect();

            let missing_attr_translation: HashSet<&_> =
                all_attributes.difference(&attributes).collect();
            for m in missing_attr_translation {
                errors.push(Error::MissingAttributeTranslation(
                    overlay.language().unwrap().clone(),
                    m.to_string(),
                ));
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::state::{
        attribute::{AttributeBuilder, AttributeType},
        encoding::Encoding,
        oca::OCABuilder,
    };
    use maplit::hashmap;

    #[test]
    fn validate_valid_oca() {
        let validator =
            Validator::new().enforce_translations(vec!["En".to_string(), "Pl".to_string()]);

        let oca = OCABuilder::new(Encoding::Utf8)
            .add_name(hashmap! {
                "En".to_string() => "Driving Licence".to_string(),
                "Pl".to_string() => "Prawo Jazdy".to_string(),
            })
            .add_description(hashmap! {
                "En".to_string() => "DL".to_string(),
                "Pl".to_string() => "PJ".to_string(),
            })
            .add_attribute(
                AttributeBuilder::new("name".to_string(), AttributeType::Text)
                    .add_label(hashmap! {
                        "En".to_string() => "Name: ".to_string(),
                        "Pl".to_string() => "Imię: ".to_string(),
                    })
                    .build(),
            )
            .add_attribute(
                AttributeBuilder::new("age".to_string(), AttributeType::Number)
                    .add_label(hashmap! {
                        "En".to_string() => "Age: ".to_string(),
                        "Pl".to_string() => "Wiek: ".to_string(),
                    })
                    .add_format("asd".to_string())
                    .build(),
            )
            .finalize();

        let result = validator.validate(&oca);

        assert!(result.is_ok());
    }

    #[test]
    fn validate_oca_with_missing_name_translation() {
        let validator =
            Validator::new().enforce_translations(vec!["En".to_string(), "Pl".to_string()]);

        let oca = OCABuilder::new(Encoding::Utf8)
            .add_name(hashmap! {
                "En".to_string() => "Driving Licence".to_string(),
            })
            .finalize();

        let result = validator.validate(&oca);

        assert!(result.is_err());
        if let Err(errors) = result {
            assert_eq!(errors.len(), 1);
        }
    }
}