|
@@ -0,0 +1,78 @@
|
|
1
|
+package SugarTrail::Template::Condition;
|
|
2
|
+# condition
|
|
3
|
+# new()
|
|
4
|
+# parse(string)
|
|
5
|
+# match(data)
|
|
6
|
+
|
|
7
|
+use strict;
|
|
8
|
+use warnings;
|
|
9
|
+
|
|
10
|
+sub _equals {
|
|
11
|
+ my $a = shift;
|
|
12
|
+ my $b = $_[0]->[0];
|
|
13
|
+ return $a eq $b;
|
|
14
|
+}
|
|
15
|
+
|
|
16
|
+sub new {
|
|
17
|
+ my $class = shift;
|
|
18
|
+ my $self = {};
|
|
19
|
+ $self->{string} = shift;
|
|
20
|
+ $self->{handlers} = {
|
|
21
|
+ '==' => \&_equals,
|
|
22
|
+ '>=' => \&_greater_or_eq,
|
|
23
|
+ '<=' => \&_less_or_eq,
|
|
24
|
+ '=@' => \&_in,
|
|
25
|
+ '=~' => \&_regex,
|
|
26
|
+ };
|
|
27
|
+ $self->{parsed} = 0;
|
|
28
|
+ return bless $self, $class;
|
|
29
|
+}
|
|
30
|
+
|
|
31
|
+# parse condition from its string version
|
|
32
|
+sub parse {
|
|
33
|
+ my $self = shift;
|
|
34
|
+ my $string = $self->{string};
|
|
35
|
+ return if $self->{parsed};
|
|
36
|
+
|
|
37
|
+ # cut spaces
|
|
38
|
+ $string =~ s/^\s+//;
|
|
39
|
+ $string =~ s/\s+$//;
|
|
40
|
+
|
|
41
|
+ # get name, operator, value(s)
|
|
42
|
+ my ($n, $o, $v) = $string =~ m/([a-zA-Z0-9_ ]+)([<>=~+\-*@]*)(.*)/;
|
|
43
|
+ return unless $n;
|
|
44
|
+
|
|
45
|
+ # cut inner spaces
|
|
46
|
+ $n =~ s/\s+$//;
|
|
47
|
+ $o =~ s/\s+$//;
|
|
48
|
+ $o =~ s/^\s+//;
|
|
49
|
+ $v =~ s/\s+$//;
|
|
50
|
+
|
|
51
|
+ # split vlues
|
|
52
|
+ my @v = split m/\s*,\s*/, $v;
|
|
53
|
+
|
|
54
|
+ # assign
|
|
55
|
+ $self->{n} = $n;
|
|
56
|
+ $self->{o} = $o;
|
|
57
|
+ $self->{v} = \@v;
|
|
58
|
+
|
|
59
|
+ $self->{parsed}++;
|
|
60
|
+}
|
|
61
|
+
|
|
62
|
+# match the cond against params
|
|
63
|
+sub match {
|
|
64
|
+ my $self = shift;
|
|
65
|
+ my $params = shift;
|
|
66
|
+ $self->parse();
|
|
67
|
+
|
|
68
|
+ my $name = $self->{n}; # what is the topic
|
|
69
|
+ my $op = $self->{o}; # what op to use
|
|
70
|
+ my $have = $self->{v}; # what we have in this step
|
|
71
|
+ my $want = $params->{$name}; # what they want
|
|
72
|
+
|
|
73
|
+ # execute the right handler
|
|
74
|
+ return &{ $self->{handlers}->{$op} }($want, $have);
|
|
75
|
+}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+1;
|