« blib/lib/auto/share/dist/Cmd-Dwarf/app/lib/Dwarf/Plugin/CGI/Session.pm
↑ Summary
blib/lib/auto/share/dist/Cmd-Dwarf/app/lib/Dwarf/Plugin/Runtime.pm »
| 1 | package Dwarf::Data::Validator; | ||
| 2 | use Dwarf::Pragma; | ||
| 3 | use Carp qw(croak); | ||
| 4 | use Data::Dumper; | ||
| 5 | use Data::Validator; | ||
| 6 | |||
| 7 | sub validate { | ||
| 8 | my ($class, $rules, $args) = @_; | ||
| 9 | my ($package, $filename, $line, $func) = caller(0); | ||
| 10 | |||
| 11 | for my $key (keys %$rules) { | ||
| 12 | if (ref $rules->{$key} eq 'HASH') { | ||
| 13 | next unless $rules->{$key}->{isa} =~ 'HashRef'; | ||
| 14 | next unless ref $rules->{$key}->{rules} eq 'HASH'; | ||
| 15 | |||
| 16 | my @args = ($args->{$key}); | ||
| 17 | @args = @{ $args->{$key} } if ref $args->{$key} eq 'ARRAY'; | ||
| 18 | |||
| 19 | for my $arg (@args) { | ||
| 20 | # Recursive Support | ||
| 21 | next unless $rules->{$key}->{rules}; | ||
| 22 | next unless ref $arg eq 'HASH'; | ||
| 23 | Dwarf::Data::Validator->validate($rules->{$key}->{rules}, $arg); | ||
| 24 | } | ||
| 25 | |||
| 26 | delete $rules->{$key}->{rules}; | ||
| 27 | next; | ||
| 28 | } | ||
| 29 | |||
| 30 | my $value = $rules->{$key}; | ||
| 31 | my ($isa, $default) = split /\s*=\s*/, $value; | ||
| 32 | |||
| 33 | $value = { isa => $isa }; | ||
| 34 | $value->{default} = $default if $default; | ||
| 35 | |||
| 36 | if ($isa =~ m/^(.+)\?$/) { | ||
| 37 | $value->{isa} = $1 . '|Undef'; | ||
| 38 | $value->{optional} = 1; | ||
| 39 | |||
| 40 | # Optional でデフォルト値がある場合、バリューが undef ならキー毎削除する | ||
| 41 | delete $args->{$key} if $default and not defined $args->{$key}; | ||
| 42 | } | ||
| 43 | |||
| 44 | $rules->{$key} = $value; | ||
| 45 | } | ||
| 46 | |||
| 47 | my $validator = Data::Validator->new(%$rules)->with(qw/NoRestricted AllowExtra NoThrow/); | ||
| 48 | my @ret = $validator->validate($args); | ||
| 49 | |||
| 50 | if ($validator->has_errors) { | ||
| 51 | my $errors = $validator->clear_errors; | ||
| 52 | my $error = Dwarf::Data::Validator->handle_errors($package, $rules, $args, $errors); | ||
| 53 | croak $error; | ||
| 54 | } | ||
| 55 | |||
| 56 | return wantarray ? @ret : \@ret; | ||
| 57 | } | ||
| 58 | |||
| 59 | sub handle_errors { | ||
| 60 | my ($class, $package, $rules, $args, $errors) = @_; | ||
| 61 | |||
| 62 | my @list; | ||
| 63 | push @list, join "", map { $_->{message} } @$errors; | ||
| 64 | push @list, '[Package] ' . $package; | ||
| 65 | push @list, '[Rules] ' . Dumper($rules); | ||
| 66 | push @list, '[Args] ' . Dumper($args); | ||
| 67 | |||
| 68 | for my $i (0 .. 100) { | ||
| 69 | my ($package, $filename, $line, $func) = caller($i); | ||
| 70 | last unless $func; | ||
| 71 | push @list, $func . " at line " . $line; | ||
| 72 | } | ||
| 73 | |||
| 74 | return join "\n", @list; | ||
| 75 | } | ||
| 76 | |||
| 77 | 1; |