| 1 | package Miril::InputValidator; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use autodie; | ||
| 6 | |||
| 7 | use List::Util qw(first); | ||
| 8 | use Data::AsObject qw(dao); | ||
| 9 | |||
| 10 | ### ACCESSORS ### | ||
| 11 | |||
| 12 | use Object::Tiny qw(validator_rx); | ||
| 13 | |||
| 14 | ### CONSTRUCTOR ### | ||
| 15 | |||
| 16 | sub new { | ||
| 17 | my $class = shift; | ||
| 18 | my $self = bless {}, $class; | ||
| 19 | |||
| 20 | $self->{validator_rx} = { | ||
| 21 | line_text => qr/.*/, | ||
| 22 | paragraph_text => qr/.*/m, | ||
| 23 | text_id => qr/^[\w\-]{1,256}$/, | ||
| 24 | datetime => qr/.*/, | ||
| 25 | integer => qr/^\d{1,8}$/, | ||
| 26 | }; | ||
| 27 | |||
| 28 | return $self; | ||
| 29 | } | ||
| 30 | |||
| 31 | ### PUBLIC METHODS ### | ||
| 32 | |||
| 33 | sub validate { | ||
| 34 | my ($self, $schema, %data) = @_; | ||
| 35 | my %invalid_fields; | ||
| 36 | |||
| 37 | |||
| 38 | |||
| 39 | foreach my $key (keys %$schema) { | ||
| 40 | my ($type, @other) = split /\s/, $schema->{$key}; | ||
| 41 | |||
| 42 | my $required = 1 if first { $_ eq 'required'} @other; | ||
| 43 | my $list = 1 if first { $_ eq 'list'} @other; | ||
| 44 | |||
| 45 | my @remaining = grep { $_ ne 'required' and $_ ne 'list' } @other; | ||
| 46 | |||
| 47 | if (@remaining) { | ||
| 48 | my $plural = 's' if @remaining > 1; | ||
| 49 | my @remaining = map {"'$_'"} @remaining; | ||
| 50 | die "Invalid option$plural " . join ',', @remaining . " supplied to validate"; | ||
| 51 | } | ||
| 52 | |||
| 53 | if ( $data{$key} ) { | ||
| 54 | push my @items_to_check, $list ? split("\0", $data{$key}) : $data{$key}; | ||
| 55 | foreach my $item_to_check (@items_to_check) { | ||
| 56 | $invalid_fields{$key}++ unless $self->_validate_type($type, $data{$key}); | ||
| 57 | } | ||
| 58 | } else { | ||
| 59 | die "Required parameter '$key' missing" if $required; | ||
| 60 | } | ||
| 61 | } | ||
| 62 | keys %invalid_fields ? return dao \%invalid_fields : return; | ||
| 63 | } | ||
| 64 | |||
| 65 | ### PRIVATE METHODS ### | ||
| 66 | |||
| 67 | sub _validate_type { | ||
| 68 | my ($self, $type, $string) = @_; | ||
| 69 | die "Illegal datatype $type" unless $self->validator_rx->{$type}; | ||
| 70 | return unless $string =~ $self->validator_rx->{$type}; | ||
| 71 | } | ||
| 72 | |||
| 73 | 1; |