QBit/Validator/Type.pm untested

filter: Statementstmt 0.0% 0 / 65 Branchbran 0.0% 0 / 18 Conditioncond 0.0% 0 / 18 MC/DCmcdc 0.0% 0 / 10 Subroutinesub 0.0% 0 / 13 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 133 CC 10 SCAR 23.8
CC
10
Cov
0%
get_checks_by_template
30.0
check
12.0
skip
6.0
CRAP 10.8
1 package QBit::Validator::Type;
2 $QBit::Validator::Type::VERSION = '0.012';
3 use qbit;
4  
5 use base qw(QBit::Class);
6  
7 use Exception::Validator;
8 use Exception::Validator::FailedField;
9  
10 sub get_all_options_name {
11 my ($self) = @_;
12  
13 return qw(message msg skip optional), $self->get_options_name(), qw(check);
14 }
15  
16 sub get_options_name {()}
17  
18 sub get_checks_by_template {
19 my ($self, $qv, $template, $path) = @_;
20  
21 $self->pre_process_template($template);
22  
23 my @checks = ();
24 my %exists_options = ();
25  
26 foreach my $option ($self->get_all_options_name()) {
27 if (exists($template->{$option})) {
28 $exists_options{$option} = TRUE;
29  
30 if ($option eq 'message' || $option eq 'msg') {
31 $qv->{'__CUSTOM_ERRORS__'} = $template->{$option};
32  
33 next;
34 }
35  
36 push(@checks, $self->{$option}->($qv, $template->{$option}, $template));
37 }
38 }
39  
40 my @unknown_options = grep {!$exists_options{$_}} keys(%$template);
41 throw gettext('Unknown options: %s for type: %s', join(', ', @unknown_options), $template->{'type'})
42 if @unknown_options;
43  
44 if (!$exists_options{'optional'} && (!exists($template->{'eq'}) || defined($template->{'eq'}))) {
45 unshift(@checks, $self->{'required'}->($qv));
46 }
47  
48 return @checks;
49 }
50  
51 sub pre_process_template {}
52  
53 sub skip {
54 my ($qv, $val, $template) = @_;
55  
56 return $val ? sub {0} : ();
57 }
58  
59 sub optional {
60 my ($qv) = @_;
61  
62 return sub {
63 return FALSE unless defined($_[1]);
64 }
65 }
66  
67 sub required {
68 my ($qv) = @_;
69  
70 return sub {
71 throw gettext('Data must be defined') unless defined $_[1];
72  
73 return TRUE;
74 }
75 }
76  
77 sub check {
78 my ($qv, $checks) = @_;
79  
80 throw Exception::Validator gettext('Option "%s" must be array of code', 'check')
81 if !defined($checks)
82 || ref($checks) ne 'ARRAY'
83 || !@$checks
84 || grep {ref($_) ne 'CODE'} @$checks;
85  
86 return sub {
87 my ($qv, $data) = @_;
88  
89 my $error;
90 my $error_msg;
91 try {
92 foreach my $check (@$checks) {
93 $check->($qv, $data);
94 }
95 }
96 catch Exception::Validator with {
97 $error = TRUE;
98 $error_msg = shift->message;
99 }
100 catch {
101 $error = TRUE;
102  
103 $qv->use_errors_handler(shift);
104  
105 $error_msg = gettext('Internal error');
106 };
107  
108 if ($error) {
109 throw FF $error_msg, check_error => TRUE;
110 }
111  
112 return TRUE;
113 }
114 }
115  
116 sub init {
117 my ($self) = @_;
118  
119 $self->SUPER::init();
120  
121 foreach (qw(skip optional required check)) {
122 $self->{$_} = \&$_;
123 }
124 }
125  
126 TRUE;