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
extern crate strfmt;

use std::collections::HashMap;
use std::fmt;

use strfmt::strfmt;

#[derive(Clone, Debug)]
pub struct Message {
    pub text: String,
    pub args: Vec<String>,
}

impl fmt::Display for Message {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut args = HashMap::new();
        for (i, a) in self.args.iter().enumerate() {
            args.insert(i.to_string(), a);
        }
        // panic if identifiers in template text won't match
        let out = strfmt(&self.text, &args).expect("message format is invalid");
        if !args.is_empty() && self.text == out {
            panic!("message does not have expected number of identifiers");
        }
        write!(f, "{}", out)
    }
}

impl PartialEq for Message {
    fn eq(&self, other: &Self) -> bool {
        if self.text != other.text {
            return false;
        }
        for (i, a) in self.args.iter().enumerate() {
            if a != &other.args[i] {
                return false;
            }
        }
        true
    }
}

#[derive(Clone, Debug)]
pub struct Feedback {
    pub field: String,
    pub messages: Vec<Message>,
}

impl PartialEq for Feedback {
    fn eq(&self, other: &Self) -> bool {
        if self.field != other.field {
            return false;
        }
        for (i, m) in self.messages.iter().enumerate() {
            if m != &other.messages[i] {
                return false;
            }
        }
        true
    }
}

#[derive(Clone, Debug)]
pub struct Error(pub Vec<Feedback>);

impl PartialEq for Error {
    fn eq(&self, other: &Self) -> bool {
        for (i, f) in self.0.iter().enumerate() {
            if f != &other.0[i] {
                return false;
            }
        }
        true
    }
}

pub mod validation;

/// validate! macro validates given fields and its inputs.
///
/// ## Examples
///
/// ```rust
/// # #[macro_use]
/// # extern crate adequate;
///
/// # use adequate::{Error, Feedback, Message};
/// # use adequate::validation::max;
///
/// # fn main() {
///     let text = "lorem ipsum dolor sit amet".to_string();
///
///     let result = validate! {
///         "name" => text => [max(9)]
///     };
///     assert!(result.is_err());
///     assert_eq!(
///         result.unwrap_err(),
///         Error(vec![
///             Feedback {
///                 field: "name".to_string(),
///                 messages: vec![
///                     Message {
///                       text: "Must not contain more characters than {0}"
///                         .to_string(),
///                       args: vec!["9".to_string()]
///                     }
///                 ]
///             }
///         ])
///     );
///
///     let result = validate! {
///         "name" => text => [max(64)],
///         "description" => text => [max(255)]
///     };
///     assert!(result.is_ok());
/// # }
/// ```
#[macro_export]
macro_rules! validate {
    ( $( $n:expr => $v:expr => [ $( $c:expr ),* ] ),* ) => {{
        let errors = vec![$(
            Feedback {
                field: $n.to_string(),
                messages: [ $( $c(&$v) ),* ]
                    .iter()
                    .cloned()
                    .filter_map(|c| c.err())
                    .collect::<Vec<_>>()
            }
        ),*]
            .iter()
            .cloned()
            .filter(|f| f.messages.len() > 0 )
            .collect::<Vec<_>>();
        if errors.len() > 0 {
            Err(Error(errors))
        } else {
            Ok(())
        }
    }};
}

#[cfg(test)]
mod test {
    use super::*;
    use super::validation::ValidationResult;

    #[test]
    fn test_message() {
        let m = Message {
            text: "lorem ipsum".to_string(),
            args: Vec::new(),
        };
        assert_eq!(m.to_string(), "lorem ipsum");

        let m = Message {
            text: "lorem {0}".to_string(),
            args: vec!["ipsum".to_string()],
        };
        assert_eq!(m.to_string(), "lorem ipsum");
    }

    #[test]
    #[should_panic]
    fn test_message_panic_with_non_numeric_tmpl_ident() {
        let m = Message {
            text: "lorem ipsum {}".to_string(),
            args: vec!["dolor".to_string()],
        };
        m.to_string();
    }

    #[test]
    #[should_panic]
    fn test_message_panic_with_missing_ident() {
        let m = Message {
            text: "lorem ipsum".to_string(),
            args: vec!["dolor".to_string()],
        };
        m.to_string();
    }

    #[test]
    #[should_panic]
    fn test_message_panic_with_missing_arg() {
        let m = Message {
            text: "lorem ipsum {0} {1}".to_string(),
            args: vec!["dolor".to_string()],
        };
        m.to_string();
    }

    #[test]
    fn test_failure() {
        let dummy = "".to_string();
        let validation = || -> Box<dyn Fn(&String) -> ValidationResult> {
            Box::new(move |_: &String| {
                Err(Message {
                    text: "Error".to_string(),
                    args: vec![],
                })
            })
        };

        let result = validate! {
            "input" => dummy => [validation()]
        };
        assert!(result.is_err());
    }

    #[test]
    fn test_success() {
        let dummy = "".to_string();
        let validation = || -> Box<dyn Fn(&String) -> ValidationResult> {
            Box::new(move |_: &String| Ok(()))
        };

        let result = validate! {
            "input" => dummy => [validation()]
        };
        assert!(result.is_ok());
    }
}