1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- package SugarTrail::Template::Condition;
- # condition
- # new()
- # parse(string)
- # match(data)
-
- use strict;
- use warnings;
-
- sub _equals {
- my $a = shift;
- my $b = $_[0]->[0];
- return $a eq $b;
- }
-
- sub _regex {
- my $a = shift;
- my $b = $_[0]->[0];
- return $a =~ m/$b/;
- }
-
- sub new {
- my $class = shift;
- my $self = {};
- $self->{string} = shift;
- $self->{handlers} = {
- '==' => \&_equals,
- '>=' => \&_greater_or_eq,
- '<=' => \&_less_or_eq,
- '=@' => \&_in,
- '=~' => \&_regex,
- };
- $self->{parsed} = 0;
- return bless $self, $class;
- }
-
- # parse condition from its string version
- sub parse {
- my $self = shift;
- my $string = $self->{string};
- return if $self->{parsed};
-
- # cut spaces
- $string =~ s/^\s+//;
- $string =~ s/\s+$//;
-
- # get name, operator, value(s)
- my ($n, $o, $v) = $string =~ m/([a-zA-Z0-9_ ]+)([<>=~+\-*@]*)(.*)/;
- return unless $n;
-
- # cut inner spaces
- $n =~ s/\s+$//;
- $o =~ s/\s+$//;
- $o =~ s/^\s+//;
- $v =~ s/\s+$//;
-
- # split vlues
- my @v = split m/\s*,\s*/, $v;
-
- # assign
- $self->{n} = $n;
- $self->{o} = $o;
- $self->{v} = \@v;
-
- $self->{parsed}++;
- }
-
- # match the cond against params
- sub match {
- my $self = shift;
- my $params = shift;
- $self->parse();
-
- my $name = $self->{n}; # what is the topic
- my $op = $self->{o}; # what op to use
- my $have = $self->{v}; # what we have in this step
- my $want = $params->{$name}; # what they want
-
- # execute the right handler
- if (exists $self->{handlers}->{$op}) {
- return &{ $self->{handlers}->{$op} }($want, $have);
- } else {
- helper::dmupp(bad_op=>$self);
- warn "unknown operator: $op\n";
- }
- }
-
-
- 1;
|