Valiant/Validates.pm

filter: Statementstmt 93.5% 246 / 263 Branchbran 79.4% 108 / 136 Conditioncond 84.7% 50 / 59 MC/DCmcdc 67.7% 21 / 31 Subroutinesub 88.6% 39 / 44 Podpod 45.0% 9 / 20 totaltotal 85.5% 473 / 553 CC 138 SCAR 26.9
CC
138
Cov
88%
__validates_for_exporter
31.4
validates
31.4
validate_only
14.1
CRAP 14.7
« Valiant/JSON/JSONBuilder.pm ↑ Summary Valiant/HTML/Tag.pm »
1 package Valiant::Validates;
2  
3 47 ▶use Moo::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 47 ▶use Module::Runtime 'use_module';
Subroutine BEGIN: called CC=1 SCAR=0.0
5 47 ▶use String::CamelCase 'camelize';
Subroutine BEGIN: called CC=1 SCAR=0.0
6 47 ▶use Scalar::Util 'blessed';
Subroutine BEGIN: called CC=1 SCAR=0.0
7 47 ▶use Valiant::Util 'throw_exception', 'debug';
Subroutine BEGIN: called CC=1 SCAR=0.0
8 47 ▶use namespace::autoclean -also => ['throw_exception', 'debug'];
Subroutine BEGIN: called CC=1 SCAR=0.0
9 47 ▶use Valiant::Validations ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 47 with 'Valiant::Translation';
12  
13 47 has _instance_validations => (is=>'rw', init_arg=>undef);
14  
15 sub push_to_i18n_lookup {
16 1 ▶ my ($class_or_self, @args) = @_;
Subroutine __push_to_i18n_lookup_for_exporter: called CC=3 SCAR=16.5
Subroutine push_to_i18n_lookup: not called CC=3 SCAR=16.5
17 1 ▶ my $class = ref($class_or_self) ? ref($class_or_self) : $class_or_self;
Branch: 2 branches
BranchTrueFalseTotal
ref $class_or_self ? : 0 1 1
ref $class_or_self ? : 0 0 0
18 1 ▶ @args = $class unless @args;
Branch: 2 branches
BranchTrueFalseTotal
unless @args 1 0 1
unless @args 0 0 0
19 1 Valiant::Validations::_add_metadata($class, 'i18n', @args);
20 }
21  
22 sub i18n_lookup {
23 2001 ▶ my ($class_or_self, $arg) = @_;
Subroutine i18n_lookup: called CC=3 SCAR=11.0
Pod undocumented
24 2001 ▶ my $class = ref($class_or_self) ? ref($class_or_self) : $class_or_self;
Branch: 1 branch
BranchTrueFalseTotal
ref $class_or_self ? : 1625 376 2001
25 47 ▶ no strict "refs";
Subroutine BEGIN: called CC=1 SCAR=0.0
26 2001 my @proposed = @{"${class}::ISA"};
27 2001 ▶ push @proposed, $class_or_self->i18n_metadata if $class_or_self->can('i18n_metadata');
Branch: 1 branch
BranchTrueFalseTotal
if $class_or_self->can("i18n_metadata") 104 1897 2001
28 2001 return grep { $_->can('model_name') } ($class, @proposed);
29 }
30  
31 sub validations {
32 934 ▶ my ($class_or_self, $arg) = @_;
Subroutine validations: called CC=8 SCAR=20.8
Pod undocumented
33 934 ▶ my $class = ref($class_or_self) ? ref($class_or_self) : $class_or_self;
Branch: 1 branch
BranchTrueFalseTotal
ref $class_or_self ? : 527 407 934
34  
35 934 my @existing = ();
36 934 ▶ if(defined($arg)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $arg) 408 526 934
37 408 ▶ if(ref($class_or_self)) { # its $self
Branch: 1 branch
BranchTrueFalseTotal
if (ref $class_or_self) { } 1 407 408
38 1 ▶ my @existing = @{ $class_or_self->_instance_validations||[] };
Branch: 1 branch
BranchTrueFalseTotal
$class_or_self->_instance_validations or [] 1 0 1
39 1 $class_or_self->_instance_validations([$arg, @existing]);
40 } else {
41 407 Valiant::Validations::_add_metadata($class_or_self, 'validations', $arg);
42 }
43 }
44 934 ▶ @existing = @{ $class_or_self->_instance_validations||[] } if ref $class_or_self;
Branch: 2 branches
BranchTrueFalseTotal
if ref $class_or_self 527 407 934
$class_or_self->_instance_validations or [] 525 2 527
45 934 ▶ my @validations = $class_or_self->validations_metadata if $class_or_self->can('validations_metadata');
Branch: 1 branch
BranchTrueFalseTotal
if $class_or_self->can("validations_metadata") 928 6 934
46 934 return @validations, @existing;
47 }
48  
49 342 ▶sub errors_class { 'Valiant::Errors' }
Subroutine errors_class: called CC=1 SCAR=0.0
Pod undocumented
50  
51 has 'errors' => (
52 is => 'ro',
53 init_arg => undef,
54 lazy => 1,
55 default => sub {
56 342 ▶ return use_module($_[0]->errors_class)
Subroutine __ANON__: called CC=1 SCAR=0.0
57 ->new(object=>$_[0], i18n=>$_[0]->i18n);
58 },
59 47 );
60  
61 sub has_errors {
62 101 ▶ return shift->errors->size ? 1:0;
Subroutine has_errors: called CC=2 SCAR=6.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
(shift())->errors->size ? : 40 61 101
63 }
64  
65 sub no_errors {
66 0 ▶ return !shift->has_errors;
Subroutine no_errors: not called CC=1 SCAR=6.9
Pod undocumented
67 }
68  
69 47 has '_context' => (is=>'rw', required=>0, predicate=>'has_context');
70  
71 0 ▶sub get_context { shift->_context }
Subroutine get_context: not called CC=1 SCAR=6.9
Pod undocumented
72  
73 sub context {
74 3 ▶ my ($self, $args) = @_;
Subroutine context: called CC=2 SCAR=6.9
Pod documented
75 3 ▶ $args = ref($args) ? $args : [$args];
Branch: 1 branch
BranchTrueFalseTotal
ref $args ? : 1 2 3
76 3 $self->_context($args);
77 3 return $self;
78 }
79  
80 47 has '_csrf_token' => (is=>'rw', required=>0, init_arg=>'csrf_token', predicate=>'has_csrf_token');
81  
82 sub csrf_token {
83 0 ▶ my ($self, $arg) = @_;
Subroutine csrf_token: not called CC=3 SCAR=24.8
Pod undocumented
84 0 ▶ $self->_csrf_token($arg) if $arg;
Branch: 1 branch
BranchTrueFalseTotal
if $arg 0 0 0
85 0 ▶ return $arg ? $self : $self->_csrf_token;
Branch: 1 branch
BranchTrueFalseTotal
$arg ? : 0 0 0
86 }
87  
88 47 has 'validated' => (is=>'rw', required=>1, init_args=>undef, default=>0);
89 47 has 'skip_validation' => (is=>'rw', required=>1, init_args=>undef, default=>0);
90  
91 sub skip_validate {
92 2 ▶ my ($self) = @_;
Subroutine skip_validate: called CC=1 SCAR=0.0
Pod documented
93 2 $self->skip_validation(1);
94 2 return $self;
95 }
96 sub do_validate {
97 0 ▶ my ($self) = @_;
Subroutine do_validate: not called CC=1 SCAR=6.9
Pod documented
98 0 $self->skip_validation(0);
99 0 return $self;
100 }
101  
102 3524 ▶sub default_validator_namepart { 'Validator' }
Subroutine default_validator_namepart: called CC=1 SCAR=0.0
Pod undocumented
103 20 ▶sub default_collection_class { 'Valiant::Validator::Collection' }
Subroutine default_collection_class: called CC=1 SCAR=0.0
Pod undocumented
104  
105 sub read_attribute_for_validation {
106 617 ▶ my ($self, $attribute) = @_;
Subroutine read_attribute_for_validation: called CC=3 SCAR=11.1
Pod undocumented
107 617 ▶ return unless defined $attribute;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $attribute 0 617 617
108 617 ▶ return my $value = $self->$attribute
Branch: 1 branch
BranchTrueFalseTotal
if $self->can($attribute) 580 37 617
109 if $self->can($attribute);
110 }
111  
112 sub _validates_coderef {
113 422 ▶ my ($self, $coderef, $attributes, %options) = @_;
Subroutine _validates_coderef: called CC=1 SCAR=0.0
114 422 $self->validations([$coderef, \%options, $attributes]);
115 422 return $self;
116 }
117  
118 sub _is_reserved_option_key {
119 655 ▶ my ($key) = @_;
Subroutine _is_reserved_option_key: called CC=9 SCAR=22.0
120 655 ▶ return 1 if $key eq 'if' || $key eq 'unless' || $key eq 'on'
Branch: 1 branch
BranchTrueFalseTotal
if $key eq "if" or $key eq "unless" or $key eq "on" or $key eq "strict" or $key eq "allow_blank" or $key eq "allow_undef" or $key eq "message" or $key eq "list" 5 614 619
Condition90%19/21
$key eq "if" or $key eq "unless" or $key eq "on" or $key eq "strict" or $key eq "allow_blank" or $key eq "allow_undef" or $key eq "message" or $key eq "list"
l!l&&r!l&&!r
410614
$key eq "if" or $key eq "unless" or $key eq "on" or $key eq "strict" or $key eq "allow_blank" or $key eq "allow_undef" or $key eq "message"
l!l&&r!l&&!r
365614
$key eq "if" or $key eq "unless" or $key eq "on" or $key eq "strict" or $key eq "allow_blank" or $key eq "allow_undef"
l!l&&r!l&&!r
342619
$key eq "if" or $key eq "unless" or $key eq "on" or $key eq "strict" or $key eq "allow_blank"
l!l&&r!l&&!r
259621
$key eq "if" or $key eq "unless" or $key eq "on" or $key eq "strict"
l!l&&r!l&&!r
241630
$key eq "if" or $key eq "unless" or $key eq "on"
l!l&&r!l&&!r
420631
$key eq "if" or $key eq "unless"
l!l&&r!l&&!r
40651
MC/DC75%6/8
$key eq "if" or $key eq "unless" or $key eq "on" or $key eq "strict" or $key eq "allow_blank" or $key eq "allow_undef" or $key eq "message" or $key eq "list"
$key eq "if" $key eq "unless" $key eq "on" $key eq "strict" $key eq "allow_blank" $key eq "allow_undef" $key eq "message" $key eq "list"
Truth table77%7/9
A or B or C or D or E or F or G or H
A= $key eq "if"B= $key eq "unless"C= $key eq "on"D= $key eq "strict"E= $key eq "allow_blank"F= $key eq "allow_undef"G= $key eq "message"H= $key eq "list"
ABCDEFGHresult
1XXXXXXX1
01XXXXXX1
001XXXXX1
0001XXXX1
00001XXX1
000001XX1
0000001X1
000000011
000000000
121 || $key eq 'strict' || $key eq 'allow_blank' || $key eq 'allow_undef'
122 || $key eq 'message' || $key eq 'list';
123 614 return 0;
124 }
125  
126 sub _prepare_validator_packages {
127 604 ▶ my ($class, $key) = @_;
Subroutine _prepare_validator_packages: called CC=2 SCAR=7.0
128 604 my $camel = camelize($key);
129 604 my @packages = $class->_normalize_validator_package($camel);
130  
131 604 ▶ return @packages if $camel =~/^\+/;
Branch: 1 branch
BranchTrueFalseTotal
if $camel =~ /^\+/ 0 604 604
132  
133 push @packages, map {
134 604 "${_}::${camel}";
135 } $class->default_validator_namespaces;
136  
137 604 return @packages;
138 }
139  
140 sub default_validator_namespaces {
141 604 ▶ my ($self) = @_;
Subroutine default_validator_namespaces: called CC=1 SCAR=0.0
Pod undocumented
142 604 return ('Valiant::ValidatorX', 'Valiant::Validator');
143 }
144  
145 sub _validator_package {
146 604 ▶ my ($self, $key) = @_;
Subroutine _validator_package: called CC=4 SCAR=14.0
147 604 my @validator_packages = $self->_prepare_validator_packages($key);
148 my ($validator_package, @rest) = grep {
149 604 my $package_to_test = $_;
150 5194 ▶ eval { use_module $package_to_test } || do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { &use_module($package_to_test) } } or do { my $notional_filename = &Module::Runtime::module_notional_filename($package_to_test); if ($@ =~ /^Can't locate $notional_filename/) { debug(1, "Can't find '${package_to_test}' in \@INC"); 0; } else { throw_exception("UnexpectedUseModuleError", ("package", $package_to_test, "err", $@)); } } 4572 622 5194
151 # This regexp matches too much... We need to add the package
152 # path here just the path delim will vary from platform to platform
153 4572 my $notional_filename = Module::Runtime::module_notional_filename($package_to_test);
154 4572 ▶ if($@=~m/^Can't locate $notional_filename/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ =~ /^Can't locate $notional_filename/) { } 4572 0 4572
155 4572 debug 1, "Can't find '$package_to_test' in \@INC";
156 4572 0;
157 } else {
158 0 throw_exception UnexpectedUseModuleError => (package => $package_to_test, err => $@);
159 }
160 }
161 } @validator_packages;
162 604 ▶ throw_exception('NameNotValidator', name => $key, packages => \@validator_packages)
Branch: 1 branch
BranchTrueFalseTotal
unless $validator_package 0 604 604
163 unless $validator_package;
164 604 debug 1, "Found $validator_package in \@INC";
165 604 return $validator_package;
166 }
167  
168 sub _create_validator {
169 604 ▶ my ($self, $validator_package, $args) = @_;
Subroutine _create_validator: called CC=1 SCAR=0.0
170 604 debug 1, "Trying to create validator from $validator_package";
171 604 my $validator = $validator_package->new($args);
172 604 return $validator;
173 }
174  
175 sub validates {
176 402 ▶ my ($self, @validation_proto) = @_;
Subroutine __validates_for_exporter: called CC=31 SCAR=34.5
177  
178 # handle a list of attributes with validations
179 402 my $attributes = shift @validation_proto;
180 402 ▶ $attributes = [$attributes] unless ref $attributes;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $attributes 390 12 402
181 402 my @options = @validation_proto;
182  
183 # We want to preserve the order of validators while stripping out global_options
184 402 my (@validator_info, %global_options) = ();
185 402 ▶ while(@options) {
Branch: 1 branch
BranchTrueFalseTotal
if (@options) 640 402 1042
186 640 my $args;
187 640 my $key = shift(@options);
188 640 ▶ if(blessed($key) && $key->can('check')) { # This bit allows for Type::Tiny instead of a validator => \%params setup
Branch: 2 branches
BranchTrueFalseTotal
if (builtin::blessed($key) and $key->can('check')) { } 1 639 640
elsif ((ref $key || '') eq 'CODE') { } 4 635 639
Condition66%2/3
builtin::blessed($key) and $key->can("check")
!ll&&!rl&&r
63901
MC/DC50%1/2
builtin::blessed($key) and $key->can("check")
builtin::blessed($key) $key->can("check")
Truth table66%2/3
A and B
A= builtin::blessed($key)B= $key->can("check")
ABresult
0X0
100
111
189 1 $args = { constraint => $key };
190 1 $key = 'check';
191 1 ▶ if((ref($options[0])||'') eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if ((ref $options[0] || "") eq "HASH") 1 0 1
Condition50%1/2
ref $options[0] || ''
l!l
10
MC/DC0%0/1
ref $options[0] || ''
ref $options[0]
Truth table50%1/2
A
A= ref $options[0]
Aresult
11
00
192 1 my $base_args = shift(@options);
193 1 $args = +{ %$args, %$base_args };
194 }
195 ▶ } elsif((ref($key)||'') eq 'CODE') { # This bit allows for callbacks instead of a validator => \%params setup
Condition100%2/2
ref $key || ''
l!l
4635
MC/DC100%1/1
ref $key || ''
ref $key
Truth table100%2/2
A
A= ref $key
Aresult
11
00
196 4 $args = { cb => $key };
197 4 $key = 'with';
198 4 ▶ if((ref($options[0])||'') eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if ((ref $options[0] || "") eq "HASH") 2 2 4
Condition100%2/2
ref $options[0] || ''
l!l
22
MC/DC100%1/1
ref $options[0] || ''
ref $options[0]
Truth table100%2/2
A
A= ref $options[0]
Aresult
11
00
199 2 my $base_args = shift(@options);
200 2 $args = +{ %$args, %$base_args };
201 }
202 } else { # Otherwise its a normal validator with params
203 635 $args = shift(@options);
204 }
205  
206 640 ▶ if(_is_reserved_option_key($key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_is_reserved_option_key($key)) { } 36 604 640
207 36 $global_options{$key} = $args;
208 } else {
209 604 push @validator_info, [$key, $args];
210 }
211 }
212  
213 402 my @validators = ();
214 402 foreach my $info(@validator_info) {
215 604 my ($package_part, $args) = @$info;
216 604 my $validator_package = $self->_validator_package($package_part);
217  
218 604 ▶ unless((ref($args)||'') eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
unless ((ref $args || "") eq "HASH") 429 175 604
Condition100%2/2
ref $args || ''
l!l
370234
MC/DC100%1/1
ref $args || ''
ref $args
Truth table100%2/2
A
A= ref $args
Aresult
11
00
219 429 $args = $validator_package->normalize_shortcut($args);
220 429 ▶ throw_exception InvalidValidatorArgs => ( args => $args) unless ref($args) eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $args eq "HASH" 0 429 429
221 }
222  
223 # so strip out the reserved and if any wrap in a conditional that
224 # way we can remove all that stuff from each
225  
226 # merge global options into args
227 604 ▶ $args->{strict} = 1 if $global_options{strict} and !exists $args->{strict};
Branch: 1 branch
BranchTrueFalseTotal
if $global_options{"strict"} and not exists $args->{"strict"} 1 603 604
Condition66%2/3
$global_options{"strict"} and not exists $args->{"strict"}
!ll&&!rl&&r
60301
MC/DC50%1/2
$global_options{"strict"} and not exists $args->{"strict"}
$global_options{"strict"} not exists $args->{"strict"}
Truth table66%2/3
A and not(B)
A= $global_options{"strict"}B= not exists $args->{"strict"}
ABresult
0X0
100
111
228 604 ▶ $args->{allow_undef} = 1 if $global_options{allow_undef} and !exists $args->{allow_undef};
Branch: 1 branch
BranchTrueFalseTotal
if $global_options{"allow_undef"} and not exists $args->{"allow_undef"} 2 602 604
Condition66%2/3
$global_options{"allow_undef"} and not exists $args->{"allow_undef"}
!ll&&!rl&&r
60202
MC/DC50%1/2
$global_options{"allow_undef"} and not exists $args->{"allow_undef"}
$global_options{"allow_undef"} not exists $args->{"allow_undef"}
Truth table66%2/3
A and not(B)
A= $global_options{"allow_undef"}B= not exists $args->{"allow_undef"}
ABresult
0X0
100
111
229 604 ▶ $args->{allow_blank} = 1 if $global_options{allow_blank} and !exists $args->{allow_blank};
Branch: 1 branch
BranchTrueFalseTotal
if $global_options{"allow_blank"} and not exists $args->{"allow_blank"} 9 595 604
Condition66%2/3
$global_options{"allow_blank"} and not exists $args->{"allow_blank"}
!ll&&!rl&&r
59509
MC/DC50%1/2
$global_options{"allow_blank"} and not exists $args->{"allow_blank"}
$global_options{"allow_blank"} not exists $args->{"allow_blank"}
Truth table66%2/3
A and not(B)
A= $global_options{"allow_blank"}B= not exists $args->{"allow_blank"}
ABresult
0X0
100
111
230 604 ▶ $args->{message} = $global_options{message} if exists $global_options{message} and !exists $args->{message};
Branch: 1 branch
BranchTrueFalseTotal
if exists $global_options{"message"} and not exists $args->{"message"} 3 601 604
Condition100%3/3
exists $global_options{"message"} and not exists $args->{"message"}
!ll&&!rl&&r
59923
MC/DC100%2/2
exists $global_options{"message"} and not exists $args->{"message"}
exists $global_options{"message"} not exists $args->{"message"}
Truth table100%3/3
A and not(B)
A= exists $global_options{"message"}B= not exists $args->{"message"}
ABresult
0X0
100
111
231  
232 604 foreach my $opt(qw(if unless on)) {
233 1812 ▶ next unless my $val = $global_options{$opt};
Branch: 1 branch
BranchTrueFalseTotal
unless my $val = $global_options{$opt} 1777 35 1812
234 35 ▶ my @val = (ref($val)||'') eq 'ARRAY' ? @$val : ($val);
Branch: 1 branch
BranchTrueFalseTotal
(ref $val || '') eq 'ARRAY' ? : 6 29 35
Condition100%2/2
ref $val || ''
l!l
1025
MC/DC100%1/1
ref $val || ''
ref $val
Truth table100%2/2
A
A= ref $val
Aresult
11
00
235 35 ▶ if(exists $args->{$opt}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $args->{$opt}) 2 33 35
236 2 my $current = $args->{$opt};
237 2 ▶ my @current = (ref($current)||'') eq 'ARRAY' ? @$current : ($current);
Branch: 1 branch
BranchTrueFalseTotal
(ref $current || '') eq 'ARRAY' ? : 0 2 2
Condition100%2/2
ref $current || ''
l!l
11
MC/DC100%1/1
ref $current || ''
ref $current
Truth table100%2/2
A
A= ref $current
Aresult
11
00
238 2 @val = (@current, @val);
239 }
240 35 $args->{$opt} = \@val;
241 }
242
243 604 $args->{attributes} = $attributes;
244 604 $args->{model_class} = $self;
245  
246 604 my $new_validator = $self->_create_validator($validator_package, $args);
247 604 push @validators, $new_validator;
248 }
249 402 ▶ my $coderef = sub { $_->validate(@_) foreach @validators };
Subroutine __ANON__: called CC=2 SCAR=6.9
250 402 $self->_validates_coderef($coderef, $attributes, %global_options);
251 }
252  
253 sub _normalize_validator_package {
254 609 ▶ my ($self, $with) = @_;
Subroutine _normalize_validator_package: called CC=4 SCAR=13.9
255 609 my ($prefix, $package) = ($with =~m/^(\+?)(.+)$/);
256 609 ▶ return $package if $prefix eq '+';
Branch: 1 branch
BranchTrueFalseTotal
if $prefix eq "+" 0 609 609
257  
258 609 ▶ my $class = ref($self) || $self;
Condition66%2/3
ref $self || $self
l!l&&r!l&&!r
195900
MC/DC0%0/2
ref $self || $self
ref $self $self
Truth table66%2/3
A || B
A= ref $selfB= $self
ABresult
1X1
011
000
259 609 my @parts = ((split '::', $class), $package);
260 609 my @project_inc = ();
261 609 ▶ while(@parts) {
Branch: 1 branch
BranchTrueFalseTotal
if (@parts) 2915 609 3524
262 2915 push @project_inc, join '::', (@parts, $class->default_validator_namepart, $package);
263 2915 pop @parts;
264 }
265 609 push @project_inc, join '::', $class->default_validator_namepart, $package; # Not sure we should allow (add flag?)
266 609 return @project_inc;
267 }
268  
269 sub _strip_reserved_options {
270 20 ▶ my (%options) = @_;
Subroutine _strip_reserved_options: called CC=3 SCAR=11.0
271 20 my %reserved = ();
272 20 foreach my $key (keys %options) {
273 15 ▶ if(_is_reserved_option_key($key)) {
Branch: 1 branch
BranchTrueFalseTotal
if (_is_reserved_option_key($key)) 5 10 15
274 5 $reserved{$key} = delete $options{$key};
275 }
276 }
277 20 return %reserved;
278 }
279  
280 sub validates_with {
281 20 ▶ my ($self, $validators_proto, %options) = @_;
Subroutine __validates_with_for_exporter: called CC=9 SCAR=22.3
282 20 my %reserved = _strip_reserved_options(%options);
283 my @with = ref($validators_proto) eq 'ARRAY' ?
284 20 ▶ @{$validators_proto} : ($validators_proto);
Branch: 1 branch
BranchTrueFalseTotal
ref $validators_proto eq 'ARRAY' ? : 0 20 20
285  
286 20 my @validators = ();
287 20 VALIDATOR_WITHS: foreach my $with (@with) {
288 20 ▶ if( (ref($with)||'') eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if ((ref $with || "") eq "CODE") 15 5 20
Condition100%2/2
ref $with || ''
l!l
155
MC/DC100%1/1
ref $with || ''
ref $with
Truth table100%2/2
A
A= ref $with
Aresult
11
00
289 15 push @validators, [$with, \%options];
290 15 next VALIDATOR_WITHS;
291 }
292 5 debug 1, "Trying to find a validator for '$with'";
293 5 my @possible_packages = $self->_normalize_validator_package($with);
294 5 foreach my $package(@possible_packages) {
295 my $found_package = eval {
296 14 use_module($package);
297 14 ▶ } || do {
Condition66%2/3
eval { || do {
l!l&&r!l&&!r
509
MC/DC50%1/2
eval { do { &use_module($package) } } || do { my $notional_filename = &Module::Runtime::module_notional_filename($package); if ($@ =~ /^Can't locate $notional_filename/) { debug(1, "Can't find '${package}' in \@INC"); 0; } else { throw_exception('UnexpectedUseModuleError', ('package', $package, 'err', $@)); } }
eval { do { &use_module($package) } } do { my $notional_filename = &Module::Runtime::module_notional_filename($package); if ($@ =~ /^Can't locate $notional_filename/) { debug(1, "Can't find '${package}' in \@INC"); 0; } else { throw_exception('UnexpectedUseModuleError', ('package', $package, 'err', $@)); } }
Truth table66%2/3
A || B
A= eval { do { &use_module($package) } }B= do { my $notional_filename = &Module::Runtime::module_notional_filename($package); if ($@ =~ /^Can't locate $notional_filename/) { debug(1, "Can't find '${package}' in \@INC"); 0; } else { throw_exception('UnexpectedUseModuleError', ('package', $package, 'err', $@)); } }
ABresult
1X1
011
000
298 9 my $notional_filename = Module::Runtime::module_notional_filename($package);
299 9 ▶ if($@=~m/^Can't locate $notional_filename/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@ =~ /^Can't locate $notional_filename/) { } 9 0 9
300 9 debug 1, "Can't find '$package' in \@INC";
301 9 0;
302 } else {
303 # Probably a syntax error in the code of $package
304 0 throw_exception UnexpectedUseModuleError => (package => $package, err => $@);
305 }
306 };
307 14 ▶ if($found_package) {
Branch: 1 branch
BranchTrueFalseTotal
if ($found_package) 5 9 14
308 5 debug 1, "Found '$found_package' in \@INC";
309 5 push @validators, $package->new(%options);
310 5 next VALIDATOR_WITHS; # Only load the first one found
311 }
312 }
313 0 throw_exception General => (msg => "Failed to find validator for '$with' in \@INC");
314 }
315 20 my $collection = use_module($self->default_collection_class)
316 ->new(validators=>\@validators, %reserved);
317 20 ▶ $self->_validates_coderef(sub { $collection->validate(@_) });
Subroutine __ANON__: called CC=1 SCAR=0.0
318 }
319  
320 sub valid {
321 221 ▶ my $self = shift;
Subroutine valid: called CC=4 SCAR=13.9
Pod documented
322 221 ▶ $self->validate(@_) if @_ || !$self->validated;
Branch: 1 branch
BranchTrueFalseTotal
if @_ or not $self->validated 20 201 221
Condition100%3/3
@_ or not $self->validated
l!l&&r!l&&!r
119201
MC/DC100%2/2
@_ or not $self->validated
@_ not $self->validated
Truth table100%3/3
A or not(B)
A= @_B= not $self->validated
ABresult
1X1
011
000
323 221 ▶ return $self->errors->size ? 0:1;
Branch: 1 branch
BranchTrueFalseTotal
$self->errors->size ? : 125 96 221
324 }
325  
326 122 ▶sub invalid { shift->valid(@_) ? 0:1 }
Subroutine invalid: called CC=2 SCAR=6.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
(shift())->valid(@_) ? : 3 119 122
327  
328 sub clear_validated {
329 201 ▶ my $self = shift;
Subroutine clear_validated: called CC=1 SCAR=0.0
Pod documented
330 201 $self->errors->clear;
331 201 $self->validated(0);
332 }
333  
334 sub validate {
335 539 ▶ my ($self, %args) = @_;
Subroutine validate: called CC=8 SCAR=20.8
Pod documented
336  
337 539 ▶ my $existing_context = $args{context} ? $args{context} : [];
Branch: 1 branch
BranchTrueFalseTotal
$args{'context'} ? : 432 107 539
338 539 ▶ my @existing_context = ref($existing_context) ? @$existing_context : ($existing_context);
Branch: 1 branch
BranchTrueFalseTotal
ref $existing_context ? : 532 7 539
339 539 ▶ push @existing_context, @{$self->_context} if $self->has_context;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_context 3 536 539
340  
341 539 ▶ $args{context} = \@existing_context if @existing_context;
Branch: 1 branch
BranchTrueFalseTotal
if @existing_context 433 106 539
342  
343 539 ▶ return $self if $self->skip_validation;
Branch: 1 branch
BranchTrueFalseTotal
if $self->skip_validation 4 535 539
344 535 ▶ return $self if $self->{_inprocess};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_inprocess"} 1 534 535
345 534 $self->{_inprocess} =1;
346  
347 534 ▶ $self->clear_validated if $self->validated;
Branch: 1 branch
BranchTrueFalseTotal
if $self->validated 198 336 534
348 534 $self->_run_validations(%args);
349 531 $self->_run_post_validations(%args);
350 531 $self->validated(1);
351 531 delete $self->{_inprocess};
352 531 return $self;
353 }
354  
355 sub validate_only {
356 3 ▶ my ($self, $attribute, %args) = @_;
Subroutine validate_only: called CC=13 SCAR=26.5
Pod documented
357 3 ▶ my @attributes = ref($attribute) ? @$attribute : ($attribute);
Branch: 1 branch
BranchTrueFalseTotal
ref $attribute ? : 1 2 3
358  
359 3 ▶ my $existing_context = $args{context} ? $args{context} : [];
Branch: 1 branch
BranchTrueFalseTotal
$args{'context'} ? : 0 3 3
360 3 ▶ my @existing_context = ref($existing_context) ? @$existing_context : ($existing_context);
Branch: 1 branch
BranchTrueFalseTotal
ref $existing_context ? : 3 0 3
361 3 ▶ push @existing_context, @{$self->_context} if $self->has_context;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_context 0 3 3
362  
363 3 ▶ $args{context} = \@existing_context if @existing_context;
Branch: 1 branch
BranchTrueFalseTotal
if @existing_context 0 3 3
364  
365 3 ▶ return $self if $self->skip_validation;
Branch: 1 branch
BranchTrueFalseTotal
if $self->skip_validation 0 3 3
366 3 ▶ return $self if $self->{_inprocess};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_inprocess"} 0 3 3
367 3 $self->{_inprocess} =1;
368  
369 3 ▶ $self->clear_validated if $self->validated;
Branch: 1 branch
BranchTrueFalseTotal
if $self->validated 2 1 3
370  
371 3 foreach my $validation ($self->validations) {
372 9 ▶ next unless $validation->[2];
Branch: 1 branch
BranchTrueFalseTotal
unless $validation->[2] 0 9 9
373 9 my @attrs_for_validation = @{$validation->[2]};
374 9 foreach my $attr (@attrs_for_validation) {
375 9 ▶ next unless grep { $_ eq $attr } @attributes;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ eq $attr;} @attributes 5 4 9
376 4 $validation->[0]($self, +{%{$validation->[1]}, %args});
377 }
378 }
379  
380 3 $self->validated(1);
381 3 delete $self->{_inprocess};
382 3 return $self;
383 }
384  
385 sub _run_validations {
386 534 ▶ my ($self, %args) = @_;
Subroutine _run_validations: called CC=2 SCAR=6.9
387 534 foreach my $validation ($self->validations) {
388 1591 my %validation_args = (%{$validation->[1]}, %args);
389 1591 $validation->[0]($self, \%validation_args);
390 }
391 }
392  
393 sub _run_post_validations {
394 531 ▶ my ($self, %args) = @_;
Subroutine _run_post_validations: called CC=1 SCAR=0.0
395 531 return;
396 }
397  
398 sub inject_attribute {
399 1 ▶ my ($class, $attribute_to_inject) = @_;
Subroutine inject_attribute: called CC=1 SCAR=0.0
Pod undocumented
400 1 eval "package $class; has $attribute_to_inject => (is=>'ro');";
401 }
402  
403 47 1;
404  
405 =head1 NAME
406  
407 Valiant::Validates - Role that adds class and instance methods supporting validations
408  
409 =head1 SYNOPSIS
410  
411 See L<Valiant>.
412  
413 =head1 DESCRIPTION
414  
415 This is a role that adds class level validations to you L<Moo> or L<Moose> classes.
416 The main point of entry for use and documentation currently is L<Valiant>. Here
417 we have API level documentation without details or examples. You should read L<Valiant>
418 first and then you can refer to documentation her for further details.
419  
420 In addition to methods this class provides, it also proves all methods from L<Valiant::Translation>
421  
422 =head1 CLASS METHODS
423  
424 =head2 validates
425  
426 Used to declare validations on an attribute. The first argument is either a scalar or arrayref of
427 scalars which should be attributes on your object:
428  
429 __PACKAGE__->validates( name => (...) );
430 __PACKAGE__->validates( ['name', 'age'] => (...));
431  
432 Following arguments should be in one of three forms: a coderef or subroutine reference that contains
433 validation rules, a key - value pair which is a validator class and its arguments or lastly you can
434 pass in a L<Type::Tiny> constraint directly. You may also have key value pairs which are global
435 arguments for the validate set as a whole:
436  
437 package Local::Model::User;
438  
439 use Moo;
440 use Valiant::Validations; # Importer that wraps Valiant::Validates
441 use Types::Standard 'Int';
442  
443 has ['name', 'age'] => (is=>'ro);
444  
445 validates name => (
446 length => { minimum => 5, maximum => 25 },
447 format => { match => 'words' },
448 sub {
449 my ($self, $attribute, $value, $opts) = @_;
450 $self->errors->add($attribute, "can't be Joe. We hate Joe :)" ,$opts) if $value eq 'Joe';
451 }, +{ arg1=>'1', arg2=>2 }, # args are optional for coderefs but are passed into $opts
452 \&must_be_unique,
453 );
454  
455 validates age => (
456 Int->where('$_ >= 65'), +{
457 message => 'A retiree must be at least 65 years old,
458 },
459 ..., # additional validations
460 );
461  
462 sub must_be_unique {
463 my ($self, $attribute, $value, $opts) = @_;
464 # Some local validation to make sure the name is unique in storage (like a database).
465 }
466  
467 If you use a validator class name then the hashref of arguments that follows is not optional. If you pass
468 an options hashref it should contain arguments that are defined for the validation type you are passing
469 or one of the global arguments: C<on>, C<message>, C<if> and C<unless>. See L</"GLOBAL OPTIONS"> for more.
470  
471 For subroutine reference and L<Type::Tiny> objects you can or not pass an options hashref depending on your
472 needs. Additionally the three types can be mixed and matched within a single C<validates> clause.
473  
474 When you use a validator class (such as C<length => { minimum => 5, maximum => 25 }>) we resolve the class
475 name C<length> in the following way. We first camel case the name and then look for a 'Validator' package
476 in the current class namespace. If we don't find a match we check each namespace up the hierarchy and
477 then check the two global namespaces C<Valiant::ValidatorX> and C<Validate::Validator>. For example if
478 you declare validators as in the example class above C<Local::Model::User> we would look for the following:
479  
480 Local::Model::User::Validator::Length
481 Local::Model:::Validator::Length
482 Local::Validator::Length
483 Validator::Length
484 Valiant::ValidatorX::Length
485 Valiant::Validator::Length
486  
487 These get checked in the order above and loaded and instantiated once at setup time.
488  
489 B<NOTE:> The namespace C<Valiant::Validator> is reserved for validators that ship with L<Valiant>. The
490 C<Valiant::ValidatorX> namespace is reserved for additional validators on CPAN that are packaged separately
491 from L<Valiant>. If you wish to share a custom validator that you wrote the proper namespace to use on
492 CPAN is C<Valiant::ValidatorX>.
493  
494 You can also prepend your validator name with '+' which will cause L<Valiant> to ignore the namespace
495 resolution and try to load the class directly. For example:
496  
497 validates_with '+App::MyValidator';
498  
499 Will try to load the class C<App::MyValidator> and use it as a validator directly (or throw an exception if
500 it fails to load).
501  
502 =head2 validates_with
503  
504 C<validates_with> is intended to process validations that are on the class as a whole, or which are very
505 complex and can't easily be assigned to a single attribute. It accepts either a subroutine reference
506 with an optional hash of key value pair options (which are passed to C<$opts>) or a scalar name which
507 should be a stand alone validator class (basically a class that does the C<validates> method although
508 you should consume the L<Validate::Validator> role to enforce the contract).
509  
510 __PACKAGE__->validates_with(sub {
511 my ($self, $opts) = @_;
512 ...
513 });
514  
515 __PACKAGE__->validates_with(\&check_object => (arg1=>'foo', arg2=>'bar'));
516  
517 sub check_object {
518 my ($self, $opts) = @_;
519 ...
520 }
521  
522 __PACKAGE__->validates with('Custom' => (arg1=>'foo', arg2=>'bar'));
523  
524 If you pass a string that is a validator class we resolve its namespace using the same approach as
525 detailed above for C<validates>. Any arguments are passed to the C<new> method of the found class
526 excluding global options.
527  
528 =head1 INSTANCE METHODS
529  
530 =head2 validate
531  
532 Run validation rules on the current object, optionally with arguments hash. If validation has already
533 been run on this object, we clear existing errors and run validations again. Currently the return
534 value of this method is not defined in the API. Example:
535  
536 $object->validate(%args);
537  
538 Currently the only arguments with defined meaning is C<context>, which is used to defined a validation
539 context. All other arguments will be passed down to the C<$opts> hashref.
540  
541 =head2 validate_only
542  
543 $obj->vadate_only('name', context=>'create');
544 $obj->validate_only(['name', 'age'], context=>'update');
545  
546 Similar to C<validate> but will run only those validations that are associated with the named
547 attribute(s). Access either a single string or arrayref of strings. Please keep in mind that
548 fields or custom validations can add errors to other fields so you may still need to check all
549 fields for errors after running this method in order to get a full picture of the object validation
550 state. However this method can be of use if you are doing AJAX per field form validation, for
551 example.
552  
553 =head2 valid
554  
555 =head2 invalid
556  
557 Return true or false depending on if the current object state is valid or not. If you call this method and
558 validations have not been run (via C<validate>) then we will first run validations and pass any arguments
559 to L</validates>. If validations have already been run we just return true or false directly UNLESS you
560 pass arguments in which case we clear errors first and then rerun validations with the arguments before
561 returning true or false.
562  
563 =head2 has_errors
564  
565 Returns a boolean indicating if the object currently has errors. This does not run a validation
566 check first (unlike C<valid> or C<invalid>). So if you just want to check the current state of
567 the errors list and not tamper with that state you can use this.
568  
569 =head2 clear_validated
570  
571 Clears any errors and sets the object as though validations hd never been run.
572  
573 =head2 do_validate
574  
575 Sets C<skip_validation> to true and returns C<$self>
576  
577 =head2 skip_validate
578  
579 Sets C<skip_validation> to false and returns C<$self>
580  
581 =head2 context
582  
583 Set a validation context (or arrayref of contexts) that will be used on an following validations.ß
584  
585 =head1 ATTRIBUTES
586  
587 =head2 errors
588  
589 An instance of L<Valiant::Errors>.
590  
591 =head2 validated
592  
593 This attribute will be true if validations have already been been run on the current instance. It
594 merely says if validations have been run or not, it does not indicate if validations have been passed
595 or failed see L</valid> pr L</invalid>
596  
597 =head2 skip_validation
598  
599 When true do not run validations, even if you call ->validate
600  
601 =head1 AUTHOR
602
603 John Napiorkowski L<email:jjnapiork@cpan.org>
604
605 =head1 SEE ALSO
606
607 L<Valiant::Validations>
608  
609 =head1 COPYRIGHT & LICENSE
610
611 Copyright 2020, John Napiorkowski L<email:jjnapiork@cpan.org>
612
613 This library is free software; you can redistribute it and/or modify it under
614 the same terms as Perl itself.
615  
616 =cut
617  
« Valiant/JSON/JSONBuilder.pm ↑ Summary Valiant/HTML/Tag.pm »