Valiant/Validator/Each.pm

filter: Statementstmt 83.9% 73 / 87 Branchbran 61.5% 32 / 52 Conditioncond 65.6% 21 / 32 MC/DCmcdc 47.0% 8 / 17 Subroutinesub 100% 11 / 11 Podpod 33.3% 1 / 3 totaltotal 72.2% 146 / 202 CC 46 SCAR 43.0
CC
46
Cov
74%
validate
105.0
generate_attributes
3.8
_requires_one_of
3.2
CRAP 73.8
« Valiant/HTML/Util/Pager.pm ↑ Summary Valiant/HTML/FormBuilder.pm »
1 package Valiant::Validator::Each;
2  
3 37 ▶use Moo::Role;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 37 ▶use Valiant::I18N; # So that _t is available in subclasses
Subroutine BEGIN: called CC=1 SCAR=0.0
5 37 ▶use Valiant::Util 'throw_exception', 'debug';
Subroutine BEGIN: called CC=1 SCAR=0.0
6 37 ▶use Scalar::Util 'blessed';
Subroutine BEGIN: called CC=1 SCAR=0.0
7 37 ▶use namespace::autoclean;
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 37 with 'Valiant::Validator';
10 37 requires 'validate_each';
11  
12 37 has allow_undef => (is=>'ro', required=>1, default=>0); # Allows undef and 'not exists'
13 37 has allow_blank => (is=>'ro', required=>1, default=>0); # A string is blank if it's empty or contains whitespaces only:
14 37 has if => (is=>'ro', predicate=>'has_if');
15 37 has unless => (is=>'ro', predicate=>'has_unless');
16 37 has on => (is=>'ro', predicate=>'has_on');
17 37 has message => (is=>'ro', predicate=>'has_message');
18 37 has strict => (is=>'ro', required=>1, default=>0);
19 126 ▶has opts => (is=>'ro', required=>1, default=>sub { +{} });
Subroutine __ANON__: called CC=1 SCAR=0.0
20 37 has attributes => (is=>'ro', required=>1);
21 37 has model_class => (is=>'ro', required=>1);
22  
23 # TODO maybe have a 'where' attribute which allows a callback so you can
24 # stick callback / coderefs all over without needed to invoke the 'with'
25 # validator.
26 #
27 # TODO do we need some sort of loop control, like 'stop_on_first_error' or
28 # something? Is possible that notion belongs in Valiant::Validatable
29  
30 372 ▶sub options {
Subroutine options: called CC=2 SCAR=6.9
Pod documented
31 372 my $self = shift;
32 my %opts = (
33 372 %{$self->opts},
34 strict => $self->strict,
35 @_);
36  
37 372 ▶ $opts{message} = $self->message if $self->has_message;
Branch: 1 branch
BranchTrueFalseTotal
if $self->has_message 17 355 372
38 372 return \%opts;
39 }
40  
41 291 ▶sub generate_attributes {
Subroutine generate_attributes: called CC=3 SCAR=13.3
Pod undocumented
42 291 my ($self, $object, $options) = @_;
43 291 ▶ if(ref($self->attributes) eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $self->attributes eq 'ARRAY') { } 291 0 291
elsif (ref $self->attributes eq 'CODE') { } 0 0 0
44 291 return @{ $self->attributes };
45 } elsif(ref($self->attributes) eq 'CODE') {
46 0 return $self->attributes->($object, $options);
47 }
48 }
49  
50 # TODO A lot of this code is redundent with ::Collection. I think we could just
51 # wrap a ::Collection over the Validators list somewhere (probably in ::Validation
52 # where we gather the Validators).
53  
54 291 ▶sub validate {
Subroutine validate: called CC=39 SCAR=46.5
Pod undocumented
55 291 my ($self, $object, $options) = @_;
56  
57 # Loop over each attribute and run the validators
58 291 ATTRIBUTE_LOOP: foreach my $attribute ($self->generate_attributes($object, $options)) {
59 342 my $value = $object->read_attribute_for_validation($attribute);
60  
61 342 ▶ next if $self->allow_undef && not(defined $value);
Branch: 1 branch
BranchTrueFalseTotal
if $self->allow_undef and not defined $value 13 329 342
Condition100%3/3
$self->allow_undef and not defined $value
!ll&&!rl&&r
322713
MC/DC100%2/2
$self->allow_undef and not defined $value
$self->allow_undef not defined $value
Truth table100%3/3
A and not(B)
A= $self->allow_undefB= not defined $value
ABresult
0X0
100
111
62 329 ▶ next if $self->allow_blank && ( not(defined $value) || $value eq '' || $value =~m/^\s+$/ );
Branch: 1 branch
BranchTrueFalseTotal
if $self->allow_blank and !defined($value) || $value eq "" || $value =~ /^\s+$/ 9 320 329
Condition77%7/9
$self->allow_blank and !defined($value) || $value eq "" || $value =~ /^\s+$/
!ll&&!rl&&r
309119
not defined $value or $value eq "" or $value =~ /^\s+$/
l!l&&r!l&&!r
9011
not defined $value or $value eq ""
l!l&&r!l&&!r
9011
MC/DC50%2/4
$self->allow_blank and !defined($value) || $value eq "" || $value =~ /^\s+$/
$self->allow_blank not defined $value $value eq "" $value =~ /^\s+$/
Truth table60%3/5
A and not(B) or C or D
A= $self->allow_blankB= not defined $valueC= $value eq ""D= $value =~ /^\s+$/
ABCDresult
0XXX0
10000
11XX1
101X1
10011
63  
64 320 ▶ if(blessed($value) && $self->allow_blank) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($value) and $self->allow_blank) 2 318 320
Condition100%3/3
builtin::blessed($value) and $self->allow_blank
!ll&&!rl&&r
276422
MC/DC100%2/2
builtin::blessed($value) and $self->allow_blank
builtin::blessed($value) $self->allow_blank
Truth table100%3/3
A and B
A= builtin::blessed($value)B= $self->allow_blank
ABresult
0X0
100
111
65 2 ▶ next if $value->can('is_blank') and $value->is_blank;
Branch: 1 branch
BranchTrueFalseTotal
if $value->can("is_blank") and $value->is_blank 0 2 2
Condition33%1/3
$value->can("is_blank") and $value->is_blank
!ll&&!rl&&r
200
MC/DC0%0/2
$value->can("is_blank") and $value->is_blank
$value->can("is_blank") $value->is_blank
Truth table33%1/3
A and B
A= $value->can("is_blank")B= $value->is_blank
ABresult
0X0
100
111
66 }
67  
68 320 ▶ if($self->has_if) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_if) 21 299 320
69 21 ▶ my @if = (ref($self->if)||'') eq 'ARRAY' ? @{$self->if} : ($self->if);
Branch: 1 branch
BranchTrueFalseTotal
(ref $self->if || '') eq 'ARRAY' ? : 6 15 21
Condition50%1/2
ref $self->if || ''
l!l
210
MC/DC0%0/1
ref $self->if || ''
ref $self->if
Truth table50%1/2
A
A= ref $self->if
Aresult
11
00
70 21 foreach my $if (@if) {
71 21 ▶ if((ref($if)||'') eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if ((ref $if || '') eq 'CODE') { } 21 0 21
Condition50%1/2
ref $if || ''
l!l
210
MC/DC0%0/1
ref $if || ''
ref $if
Truth table50%1/2
A
A= ref $if
Aresult
11
00
72 21 ▶ next ATTRIBUTE_LOOP unless $if->($object, $attribute, $value, $options);
Branch: 1 branch
BranchTrueFalseTotal
unless &$if($object, $attribute, $value, $options) 15 6 21
73 } else {
74 0 ▶ if(my $method_cb = $object->can($if)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $method_cb = $object->can($if)) { } 0 0 0
75 0 ▶ next ATTRIBUTE_LOOP unless $method_cb->($object, $attribute, $value, $options);
Branch: 1 branch
BranchTrueFalseTotal
unless &$method_cb($object, $attribute, $value, $options) 0 0 0
76 } else {
77 0 throw_exception MissingMethod => (object=>$object, method=>$if);
78 }
79 }
80 }
81 }
82 305 ▶ if($self->has_unless) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_unless) 0 305 305
83 0 ▶ my @unless = (ref($self->unless)||'') eq 'ARRAY' ? @{$self->unless} : ($self->unless);
Branch: 1 branch
BranchTrueFalseTotal
(ref $self->unless || '') eq 'ARRAY' ? : 0 0 0
Condition0%0/2
ref $self->unless || ''
l!l
00
MC/DC0%0/1
ref $self->unless || ''
ref $self->unless
Truth table0%0/2
A
A= ref $self->unless
Aresult
11
00
84 0 foreach my $unless (@unless) {
85 0 ▶ if((ref($unless)||'') eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if ((ref $unless || '') eq 'CODE') { } 0 0 0
Condition0%0/2
ref $unless || ''
l!l
00
MC/DC0%0/1
ref $unless || ''
ref $unless
Truth table0%0/2
A
A= ref $unless
Aresult
11
00
86 0 ▶ next ATTRIBUTE_LOOP if $unless->($object, $attribute, $value, $options);
Branch: 1 branch
BranchTrueFalseTotal
if &$unless($object, $attribute, $value, $options) 0 0 0
87 } else {
88 0 ▶ if(my $method_cb = $object->can($unless)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $method_cb = $object->can($unless)) { } 0 0 0
89 0 ▶ next ATTRIBUTE_LOOP if $method_cb->($object, $attribute, $value, $options);
Branch: 1 branch
BranchTrueFalseTotal
if &$method_cb($object, $attribute, $value, $options) 0 0 0
90 } else {
91 0 throw_exception MissingMethod => (object=>$object, method=>$unless);
92 }
93 }
94 }
95 }
96  
97 305 ▶ if($self->has_on) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_on) 26 279 305
98 26 ▶ my @on = ref($self->on) ? @{$self->on} : ($self->on);
Branch: 1 branch
BranchTrueFalseTotal
ref $self->on ? : 22 4 26
99 26 ▶ my $context = $options->{context}||'';
Condition100%2/2
$options->{'context'} || ''
l!l
1610
MC/DC100%1/1
$options->{'context'} || ''
$options->{'context'}
Truth table100%2/2
A
A= $options->{'context'}
Aresult
11
00
100 26 ▶ my @context = ref($context) ? @$context : ($context);
Branch: 1 branch
BranchTrueFalseTotal
ref $context ? : 16 10 26
101 26 my $matches = 0;
102  
103 26 OUTER: foreach my $c (@context) {
104 28 foreach my $o (@on) {
105 34 ▶ if($c eq $o) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c eq $o) 11 23 34
106 11 $matches = 1;
107 11 last OUTER;
108 }
109 }
110 }
111  
112 26 ▶ next unless $matches;
Branch: 1 branch
BranchTrueFalseTotal
unless $matches 15 11 26
113 }
114  
115 290 ▶ $self->validate_each($object, $attribute, $value, $self->options(%{$options||+{}}) );
Condition50%1/2
$options || {}
l!l
2900
MC/DC0%0/1
$options || {}
$options
Truth table50%1/2
A
A= $options
Aresult
11
00
116 }
117 }
118  
119 50 ▶sub _requires_one_of {
Subroutine _requires_one_of: called CC=3 SCAR=11.7
120 50 my ($self, $args, @list) = @_;
121 50 foreach my $arg (@list) {
122 88 ▶ return if defined($args->{$arg});
Branch: 1 branch
BranchTrueFalseTotal
if defined $args->{$arg} 50 38 88
123 }
124 0 my $list = join ', ', @list;
125 0 throw_exception General => (msg => "Missing at least one of the following args: $list");
126 }
127  
128 172 ▶sub _cb_value {
Subroutine _cb_value: called CC=3 SCAR=11.0
129 172 my ($self, $object, $value) = @_;
130 172 ▶ if((ref($value)||'') eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if ((ref $value || '') eq 'CODE') { } 40 132 172
Condition100%2/2
ref $value || ''
l!l
69103
MC/DC100%1/1
ref $value || ''
ref $value
Truth table100%2/2
A
A= ref $value
Aresult
11
00
131 40 return $value->($object, $self);
132 } else {
133 132 return $value;
134 }
135 }
136  
137 37 1;
138  
139 =head1 NAME
140  
141 Valiant::Validator::Each - A Role to create custom validators
142  
143 =head1 SYNOPSIS
144  
145 package Valiant::Validator::Presence;
146  
147 use Moo;
148 use Valiant::I18N;
149  
150 with 'Valiant::Validator::Each';
151  
152 has required => (is=>'ro', init_arg=>undef, required=>1, default=>1 );
153 has is_blank => (is=>'ro', required=>1, default=>sub {_t 'is_blank'});
154  
155 sub normalize_shortcut {
156 my ($class, $arg) = @_;
157 return +{} if $arg eq '1' ;
158 }
159  
160 sub validate_each {
161 my ($self, $record, $attribute, $value, $opts) = @_;
162 if(
163 not(defined $value) ||
164 $value eq '' ||
165 $value =~m/^\s+$/
166 ) {
167 $record->errors->add($attribute, $self->is_blank, $opts)
168 }
169 }
170
171 package Local::User;
172  
173 use Moo;
174 use Valiant::Validations;
175  
176 has name => (is=>'ro');
177 has age => (is=>'ro);
178  
179 validates ['name', 'age'],
180 Presence => 1;
181  
182 =head1 DESCRIPTION
183  
184 Use this role when you with to create a custom validator that will be run
185 on your class attributes. Please note
186 that you can also use the 'with' validator (L<Valiant::Validator::With>)
187 for simple custom validation needs. Its best to use this role when you
188 want custom validation that is going to be shared across several classes
189 so the effort pays off in reuse.
190  
191 Your class must provide the method C<validate_each>, which will be called
192 once for each attribute in the validation.
193  
194 In addition to providing validation control this role also provides a
195 few utility method to make creating new validators easier.
196  
197 =head1 ATTRIBUTES
198  
199 This validator role provides the following attributes
200  
201 =head2 allow_undef
202  
203 If the attribute value is undef, skip validation and allow it
204  
205 =head2 allow_blank
206  
207 If the attribute is blank (that is its one of undef, '', or a scalar composing only
208 whitespace) skip validation and allow it.
209  
210 =head2 if / unless
211  
212 Accepts a coderef or the name of a method which executes and is expected to
213 return true or false. If false we skip the validation (or true for C<unless>).
214 Recieves the object, the attribute name and the value to be checked as arguments.
215  
216 You can set more than one value to these with an arrayref:
217  
218 if => ['is_admin', sub { ... }, 'active_account'],
219  
220 =head2 message
221  
222 Provide a global error message override for the constraint. Will accept a string,
223 a translation tag, a reference to a string or a reference to a function. Using
224 this will override the custom error message provided by the validator.
225  
226 Please not that many validators also
227 provide error type specific messages for providing custom errors (as well as
228 the ability to setup your own errors in a localization file. Using this attribute
229 is the easiest but probably not always your best option.
230  
231 =head2 strict
232  
233 When true instead of adding a message to the errors list, will throw exception with the
234 error instead. If the true value is the name of a class that provides a C<throw>
235 message, will use that instead.
236  
237 =head2 on
238  
239 A scalar or list of contexts that can be used to control the situation ('context')
240 under which the validation is executed. If you specify an C<on> context that
241 validation will only run if you pass that context via C<validate>. However if you
242 don't set a context for the validate (in other words you don't set an C<on> value)
243 then that validation ALWAYS runs (whether or not you set a context via C<validates>.
244 Basically not setting a context means validation runs in all contexts and none.
245  
246 =head1 METHODS
247  
248 This role provides the following methods. You may wish to review the source
249 code of the prebuild validators for examples of usage.
250  
251 =head2 options
252  
253 Used to properly construct a options hashref that you should pass to any
254 calls to add an error. You need this for passing special values to the translation
255 method or for setting overrides such as C<strict> or C<message>.
256  
257 =head2 _cb_value
258  
259 Quite often you wish to give your users the flexibility in providing values
260 to your validation fields from a callback or as a method on the underlying
261 object. That way you can avoid always hardcoding your requirements or make
262 them subject to certain conditions. For example you may allow users added
263 before a certain date to continue to use a username with few characters than
264 newer ones, etc.
265  
266 In order to do this you can run C<_cb_value> on the actual attribute value and if
267 that value is a coderef it will get invoked with the object you are validating and
268 the instance of the validator (in case the validator instance has some useful helper
269 methods). In any case you should use this method to get attribute
270 values that are used for doing validations:
271  
272 sub validate_each {
273 my ($self, $record, $attribute, $value, $options) = @_;
274 my $state = $self->_cb_value($record, $self->state);
275 my %opts = (%{$self->options}, %{$options||+{}});
276  
277 if($state) {
278 # value must be true
279 unless($value) {
280 $record->errors->add($attribute, $self->is_not_true, \%opts);
281 }
282 } else {
283 # value must be false
284 if ($value) {
285 $record->errors->add($attribute, $self->is_not_false, \%opts);
286 }
287 }
288 }
289  
290 =head2 _requires_one_of
291  
292 Given a list of arguments will return true if at least once of them appears.
293 Useful for when you are writing a validator with several optional approachs
294 to validation and you want to make sure the user chose at least one of them.
295  
296 =head1 SEE ALSO
297
298 L<Valiant>, L<Valiant::Validator>, L<Valiant::Validator::Each>.
299  
300 =head1 AUTHOR
301
302 See L<Valiant>
303
304 =head1 COPYRIGHT & LICENSE
305
306 See L<Valiant>
307  
308 =cut
« Valiant/HTML/Util/Pager.pm ↑ Summary Valiant/HTML/FormBuilder.pm »