14
14
15
15
use mlua:: UserData ;
16
16
use tealr:: TypeName ;
17
+ use regex:: Regex ;
17
18
18
19
#[ derive( TypeName , Debug ) ]
19
20
pub struct ResponseMatcher { }
20
21
21
22
impl ResponseMatcher {
22
- pub fn match_and_body ( & self , body : String , text : Vec < String > ) -> bool {
23
+ pub fn match_and_body ( & self , body : & str , text : Vec < String > , is_regex : Option < bool > ) -> bool {
23
24
let mut counter = 0 ;
24
- text. iter ( ) . for_each ( |x| {
25
- if body. contains ( x) {
25
+ for x in text. iter ( ) {
26
+ if is_regex. unwrap_or ( false ) {
27
+ if let Ok ( re_pattern) = Regex :: new ( x) {
28
+ if re_pattern. is_match ( body) {
29
+ counter += 1 ;
30
+ }
31
+ }
32
+ } else if body. contains ( x) {
26
33
counter += 1 ;
27
34
}
28
- } ) ;
29
- if counter == text. len ( ) {
30
- true
31
- } else {
32
- false
33
35
}
36
+ counter == text. len ( )
34
37
}
35
- pub fn match_once_body ( & self , body : String , text : Vec < String > ) -> String {
36
- let mut matched_data = "" . into ( ) ;
37
- text. iter ( ) . for_each ( |x| {
38
- if body. contains ( x) {
39
- matched_data = x. to_string ( ) ;
38
+
39
+ pub fn match_once_body ( & self , body : String , text : Vec < String > , is_regex : Option < bool > ) -> Vec < String > {
40
+ let mut matched_data = Vec :: new ( ) ;
41
+ for pattern in text {
42
+ if is_regex. unwrap_or ( false ) {
43
+ if let Ok ( re) = Regex :: new ( & pattern) {
44
+ if re. is_match ( & body) {
45
+ matched_data. push ( pattern) ;
46
+ }
47
+ }
48
+ } else if body. contains ( & pattern) {
49
+ matched_data. push ( pattern) ;
40
50
}
41
- } ) ;
51
+ }
42
52
matched_data
43
53
}
44
54
}
@@ -47,14 +57,14 @@ impl UserData for ResponseMatcher {
47
57
fn add_methods < ' lua , M : mlua:: UserDataMethods < ' lua , Self > > ( methods : & mut M ) {
48
58
methods. add_method (
49
59
"match_body" ,
50
- |_, this, ( response, text_list) : ( String , Vec < String > ) | {
51
- Ok ( this. match_and_body ( response, text_list) )
60
+ |_, this, ( response, text_list, is_regex ) : ( String , Vec < String > , Option < bool > ) | {
61
+ Ok ( this. match_and_body ( & response, text_list, is_regex ) )
52
62
} ,
53
63
) ;
54
64
methods. add_method (
55
65
"match_body_once" ,
56
- |_, this, ( response, text_list) : ( String , Vec < String > ) | {
57
- let is_match = this. match_once_body ( response, text_list) ;
66
+ |_, this, ( response, text_list, is_regex ) : ( String , Vec < String > , Option < bool > ) | {
67
+ let is_match = this. match_once_body ( response, text_list, is_regex ) ;
58
68
Ok ( is_match)
59
69
} ,
60
70
)
0 commit comments