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
use std::collections::BTreeSet;

use async_graphql::{InputObject, InputType};

use super::components::{source, ComponentKind};

/// Takes an `&Option<bool>` and returns early if false
#[macro_export]
macro_rules! filter_check {
    ($($match:expr),+) => {
        $(
            if matches!($match, Some(t) if !t) {
                return false;
            }
        )+
    }
}

#[derive(Default, InputObject)]
/// Filter for String values
pub struct StringFilter {
    pub equals: Option<String>,
    pub not_equals: Option<String>,
    pub contains: Option<String>,
    pub not_contains: Option<String>,
    pub starts_with: Option<String>,
    pub ends_with: Option<String>,
}

impl StringFilter {
    pub fn filter_value(&self, value: &str) -> bool {
        filter_check!(
            // Equals
            self.equals.as_ref().map(|s| value.eq(s)),
            // Not equals
            self.not_equals.as_ref().map(|s| !value.eq(s)),
            // Contains
            self.contains.as_ref().map(|s| value.contains(s)),
            // Does not contain
            self.not_contains.as_ref().map(|s| !value.contains(s)),
            // Starts with
            self.starts_with.as_ref().map(|s| value.starts_with(s)),
            // Ends with
            self.ends_with.as_ref().map(|s| value.ends_with(s))
        );
        true
    }
}

#[derive(InputObject)]
#[graphql(concrete(name = "SourceOutputTypeFilter", params(source::SourceOutputType)))]
// Filter for GraphQL lists
pub struct ListFilter<T: InputType + PartialEq + Eq + Ord> {
    pub equals: Option<Vec<T>>,
    pub not_equals: Option<Vec<T>>,
    pub contains: Option<T>,
    pub not_contains: Option<T>,
}

impl<T: InputType + PartialEq + Eq + Ord> ListFilter<T> {
    pub fn filter_value(&self, value: Vec<T>) -> bool {
        let val = BTreeSet::from_iter(value.iter());
        filter_check!(
            // Equals
            self.equals
                .as_ref()
                .map(|s| BTreeSet::from_iter(s.iter()).eq(&val)),
            // Not Equals
            self.not_equals
                .as_ref()
                .map(|s| !BTreeSet::from_iter(s.iter()).eq(&val)),
            // Contains
            self.contains.as_ref().map(|s| val.contains(s)),
            // Not Contains
            self.not_contains.as_ref().map(|s| !val.contains(s))
        );
        true
    }
}

#[derive(InputObject)]
#[graphql(concrete(name = "ComponentKindFilter", params(ComponentKind)))]
pub struct EqualityFilter<T: InputType + PartialEq + Eq> {
    pub equals: Option<T>,
    pub not_equals: Option<T>,
}

impl<T: InputType + PartialEq + Eq> EqualityFilter<T> {
    pub fn filter_value(&self, value: T) -> bool {
        filter_check!(
            // Equals
            self.equals.as_ref().map(|s| value.eq(s)),
            // Not equals
            self.not_equals.as_ref().map(|s| !value.eq(s))
        );
        true
    }
}

/// CustomFilter trait to determine whether to include/exclude fields based on matches.
pub trait CustomFilter<T> {
    fn matches(&self, item: &T) -> bool;
    fn or(&self) -> Option<&Vec<Self>>
    where
        Self: Sized;
}

/// Returns true if a provided `Item` passes all 'AND' or 'OR' filter rules, recursively.
fn filter_item<Item, Filter>(item: &Item, f: &Filter) -> bool
where
    Filter: CustomFilter<Item>,
{
    f.matches(item)
        || f.or()
            .map_or_else(|| false, |f| f.iter().any(|f| filter_item(item, f)))
}

/// Filters items based on an implementation of `CustomFilter<T>`.
pub fn filter_items<Item, Iter, Filter>(items: Iter, f: &Filter) -> Vec<Item>
where
    Iter: Iterator<Item = Item>,
    Filter: CustomFilter<Item>,
{
    items.filter(|c| filter_item(c, f)).collect()
}

#[cfg(test)]
mod test {
    use super::StringFilter;

    #[test]
    fn string_equals() {
        let value = "test";

        let sf = StringFilter {
            equals: value.to_string().into(),
            ..Default::default()
        };

        assert!(sf.filter_value(value));
        assert!(!sf.filter_value("not found"));
    }

    #[test]
    fn string_not_equals() {
        let value = "value";
        let diff_value = "different value";

        let sf = StringFilter {
            not_equals: diff_value.to_string().into(),
            ..Default::default()
        };

        assert!(sf.filter_value(value));
        assert!(!sf.filter_value(diff_value));
    }

    #[test]
    fn string_contains() {
        let sf = StringFilter {
            contains: "234".to_string().into(),
            ..Default::default()
        };

        assert!(sf.filter_value("12345"));
        assert!(!sf.filter_value("xxx"));
    }

    #[test]
    fn string_not_contains() {
        let contains = "xyz";

        let sf = StringFilter {
            not_contains: contains.to_string().into(),
            ..Default::default()
        };

        assert!(sf.filter_value("abc"));
        assert!(!sf.filter_value(contains));
    }

    #[test]
    fn string_starts_with() {
        let sf = StringFilter {
            starts_with: "abc".to_string().into(),
            ..Default::default()
        };

        assert!(sf.filter_value("abcdef"));
        assert!(!sf.filter_value("xyz"));
    }

    #[test]
    fn string_ends_with() {
        let sf = StringFilter {
            ends_with: "456".to_string().into(),
            ..Default::default()
        };

        assert!(sf.filter_value("123456"));
        assert!(!sf.filter_value("123"));
    }

    #[test]
    fn string_multiple_all_match() {
        let value = "123456";
        let sf = StringFilter {
            equals: value.to_string().into(),
            not_equals: "xyz".to_string().into(),
            contains: "234".to_string().into(),
            not_contains: "678".to_string().into(),
            starts_with: "123".to_string().into(),
            ends_with: "456".to_string().into(),
        };

        assert!(sf.filter_value(value));
        assert!(!sf.filter_value("should fail"));
    }
}