| 1 | #!perl | ||
| 2 | |||
| 3 | # ########################################################################## # | ||
| 4 | # Title: Row value validator | ||
| 5 | # Creation date: 2007-03-05 | ||
| 6 | # Author: Michael Zedeler | ||
| 7 | # Description: Validate data in stream using regular expressions | ||
| 8 | # Data Stream class | ||
| 9 | # Data transformer | ||
| 10 | # File: $Source: /data/cvs/lib/DSlib/lib/DS/Transformer/Validator.pm,v $ | ||
| 11 | # Repository: kronhjorten | ||
| 12 | # State: $State: Exp $ | ||
| 13 | # Documentation: inline | ||
| 14 | # Recepient: - | ||
| 15 | # ########################################################################## # | ||
| 16 | |||
| 17 | package DS::Transformer::Validator; | ||
| 18 | |||
| 19 | use base qw{ DS::Transformer::TypePassthrough }; | ||
| 20 | |||
| 21 | use strict; | ||
| 22 | use warnings; | ||
| 23 | |||
| 24 | use DS::Exception::Processing::Validator; | ||
| 25 | |||
| 26 | our ($VERSION) = $DS::VERSION; | ||
| 27 | our ($REVISION) = '$Revision: 1.1 $' =~ /(\d+\.\d+)/; | ||
| 28 | |||
| 29 | |||
| 30 | sub new { | ||
| 31 | my( $class, $constraints, $fail_handler, $source, $target ) = @_; | ||
| 32 | |||
| 33 | my $self = $class->SUPER::new( $source, $target ); | ||
| 34 | |||
| 35 | $self->{constraints} = $constraints; | ||
| 36 | $self->{fail_handler} = $fail_handler; | ||
| 37 | |||
| 38 | return $self; | ||
| 39 | } | ||
| 40 | |||
| 41 | sub process { | ||
| 42 | my( $self, $row ) = @_; | ||
| 43 | |||
| 44 | if( $row ) { | ||
| 45 | foreach my $field (keys %{$self->{constraints}}) { | ||
| 46 | |||
| 47 | my $re = $self->{constraints}->{$field}; | ||
| 48 | if(not exists $row->{$field}) { | ||
| 49 | die "Fatal error: the field $field does not exist."; | ||
| 50 | } elsif( defined( $row->{$field} ) ) { | ||
| 51 | if($row->{$field} !~ /$re/) { | ||
| 52 | my %error = ( | ||
| 53 | message => "Constraint check failed: field $field with value \"" | ||
| 54 | . $row->{$field} | ||
| 55 | . "\" does not match regex $re", | ||
| 56 | row => {%$row}, | ||
| 57 | field => $field, | ||
| 58 | regex => $re, | ||
| 59 | validator => $self | ||
| 60 | ); | ||
| 61 | if( $self->{fail_handler} ) { | ||
| 62 | &{$self->{fail_handler}}( {%error} ); | ||
| 63 | } else { | ||
| 64 | DS::Exception::Processing::Validator->throw( %error ); | ||
| 65 | } | ||
| 66 | } | ||
| 67 | } | ||
| 68 | } | ||
| 69 | } | ||
| 70 | |||
| 71 | return $row; | ||
| 72 | } | ||
| 73 | |||
| 74 | 1; | ||
| 75 | |||
| 76 |