Valiant/Validator/Date.pm

filter: Statementstmt 81.8% 81 / 99 Branchbran 81.2% 26 / 32 Conditioncond 37.5% 3 / 8 MC/DCmcdc 0.0% 0 / 5 Subroutinesub 75.0% 21 / 28 Podpod 58.3% 7 / 12 totaltotal 75.0% 138 / 184 CC 20 SCAR 16.8
CC
20
Cov
79%
validate_each
12.0
normalize_shortcut
9.8
parse_if_needed
4.5
CRAP 5.4
« Valiant/Naming.pm ↑ Summary Valiant/Util/Exception/MissingMethod.pm »
1 package Valiant::Validator::Date;
2  
3 7 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 7 ▶use Valiant::I18N;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 7 ▶use DateTime;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 7 ▶use DateTime::Format::Strptime;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 7 ▶use Scalar::Util 'blessed';
Subroutine BEGIN: called CC=1 SCAR=0.0
8  
9 7 our $_pattern = '%Y-%m-%d';
10  
11 7 with 'Valiant::Validator::Each';
12  
13 7 has min => (is=>'ro', required=>0, predicate=>'has_min');
14 7 has max => (is=>'ro', required=>0, predicate=>'has_max');
15 7 has min_eq => (is=>'ro', required=>0, predicate=>'has_min_eq');
16 7 has max_eq => (is=>'ro', required=>0, predicate=>'has_max_eq');
17  
18 7 has cb => (is=>'ro', required=>0, predicate=>'has_cb');
19  
20 8 ▶has pattern => (is=>'ro', required=>1, default=>sub { $_pattern });
Subroutine __ANON__: called CC=1 SCAR=0.0
21  
22 has _strp => (
23 is=>'ro',
24 required=>1,
25 lazy=>1,
26 default=>sub {
27 7 ▶ my $self = shift;
Subroutine __ANON__: called CC=1 SCAR=0.0
28 7 return DateTime::Format::Strptime->new(time_zone=>$self->tz, pattern => $self->pattern);
29 },
30 7 );
31  
32  
33 8 ▶has below_min_msg => (is=>'ro', required=>1, default=>sub {_t 'below_min'});
Subroutine __ANON__: called CC=1 SCAR=0.0
34 8 ▶has below_min_eq_msg => (is=>'ro', required=>1, default=>sub {_t 'below_min_eq'});
Subroutine __ANON__: called CC=1 SCAR=0.0
35 8 ▶has above_max_msg => (is=>'ro', required=>1, default=>sub {_t 'above_max'});
Subroutine __ANON__: called CC=1 SCAR=0.0
36 8 ▶has above_max_eq_msg => (is=>'ro', required=>1, default=>sub {_t 'above_max_eq'});
Subroutine __ANON__: called CC=1 SCAR=0.0
37  
38 8 ▶has invalid_date_msg => (is=>'ro', required=>1, default=>sub {_t 'invalid_date'});
Subroutine __ANON__: called CC=1 SCAR=0.0
39  
40 8 ▶has tz => (is=>'ro', required=>1, default=>sub { 'UTC' });
Subroutine __ANON__: called CC=1 SCAR=0.0
41  
42 sub normalize_shortcut {
43 2 ▶ my ($class, $arg) = @_;
Subroutine normalize_shortcut: called CC=6 SCAR=22.8
Pod undocumented
44 2 ▶ return +{ } if $arg eq '1';
Branch: 1 branch
BranchTrueFalseTotal
if $arg eq 1 0 2 2
45 2 ▶ return +{ cb => $arg } if ((ref($arg)||'') eq 'CODE');
Branch: 1 branch
BranchTrueFalseTotal
if (ref $arg || "") eq "CODE" 0 2 2
Condition50%1/2
ref $arg || ''
l!l
02
MC/DC0%0/1
ref $arg || ''
ref $arg
Truth table50%1/2
A
A= ref $arg
Aresult
11
00
46 2 ▶ return +{ min => sub { pop->now } } if $arg eq 'is_future';
Subroutine __ANON__: called CC=1 SCAR=0.2
Branch: 1 branch
BranchTrueFalseTotal
if $arg eq "is_future" 2 0 2
47 0 ▶ return +{ max => sub { pop->now } } if $arg eq 'is_past';
Subroutine __ANON__: not called CC=1 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
if $arg eq "is_past" 0 0 0
48  
49 }
50  
51 sub validate_each {
52 56 ▶ my ($self, $record, $attribute, $value, $opts) = @_;
Subroutine validate_each: called CC=12 SCAR=24.8
Pod undocumented
53
54 56 ▶ unless(defined $value) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $value) 4 52 56
55 4 $record->errors->add($attribute, $self->invalid_date_msg, $opts);
56 4 return;
57 }
58  
59 52 my $dt = $self->_strp->parse_datetime($value);
60  
61 52 ▶ unless($dt) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($dt) 2 50 52
62 2 $record->errors->add($attribute, $self->invalid_date_msg, $opts);
63 2 return;
64 }
65  
66 50 ▶ if($self->has_min) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_min) 46 4 50
67 46 my $min = $self->_cb_value($record, $self->min);
68 46 my $min_dt_obj = $self->parse_if_needed($min);
69 46 ▶ $record->errors->add($attribute, $self->below_min_msg, +{%$opts, min=>$min_dt_obj->strftime($self->pattern)})
Branch: 1 branch
BranchTrueFalseTotal
unless $dt > $min_dt_obj 4 42 46
70 unless $dt > $min_dt_obj;
71 }
72  
73 50 ▶ if($self->has_max) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_max) 41 9 50
74 41 my $max = $self->_cb_value($record, $self->max);
75 41 my $max_dt_obj = $self->parse_if_needed($max);
76 41 ▶ $record->errors->add($attribute, $self->above_max_msg, +{%$opts, max=>$max_dt_obj->strftime($self->pattern)})
Branch: 1 branch
BranchTrueFalseTotal
unless $dt < $max_dt_obj 2 39 41
77 unless $dt < $max_dt_obj;
78 }
79  
80 50 ▶ if($self->has_min_eq) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_min_eq) 4 46 50
81 4 my $min = $self->_cb_value($record, $self->min_eq);
82 4 my $min_dt_obj = $self->parse_if_needed($min);
83 4 ▶ $record->errors->add($attribute, $self->below_min_eq_msg, +{%$opts, min=>$min_dt_obj->strftime($self->pattern)})
Branch: 1 branch
BranchTrueFalseTotal
unless $dt >= $min_dt_obj 1 3 4
84 unless $dt >= $min_dt_obj;
85 }
86  
87 50 ▶ if($self->has_max_eq) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_max_eq) 4 46 50
88 4 my $max = $self->_cb_value($record, $self->max_eq);
89 4 my $max_dt_obj = $self->parse_if_needed($max);
90 4 ▶ $record->errors->add($attribute, $self->above_max_eq_msg, +{%$opts, max=>$max_dt_obj->strftime($self->pattern)})
Branch: 1 branch
BranchTrueFalseTotal
unless $dt <= $max_dt_obj 1 3 4
91 unless $dt <= $max_dt_obj;
92 }
93  
94 50 ▶ if($self->has_cb) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->has_cb) 8 42 50
95 8 $self->cb->($record, $attribute, $dt, $self, $opts);
96 }
97 }
98  
99 sub to_pattern {
100 0 ▶ my ($self, $dt) = @_;
Subroutine to_pattern: not called CC=1 SCAR=6.9
Pod undocumented
101 0 return $dt->strftime($self->pattern);
102 }
103  
104 sub parse_if_needed {
105 95 ▶ my ($self, $value_proto) = @_;
Subroutine parse_if_needed: called CC=3 SCAR=15.1
Pod undocumented
106 95 ▶ return $value_proto if blessed($value_proto) && $value_proto->isa('DateTime');
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($value_proto) and $value_proto->isa("DateTime") 95 0 95
Condition33%1/3
builtin::blessed($value_proto) and $value_proto->isa("DateTime")
!ll&&!rl&&r
0095
MC/DC0%0/2
builtin::blessed($value_proto) and $value_proto->isa("DateTime")
builtin::blessed($value_proto) $value_proto->isa("DateTime")
Truth table33%1/3
A and B
A= builtin::blessed($value_proto)B= $value_proto->isa("DateTime")
ABresult
0X0
100
111
107 0 my $dt = $self->_strp->parse_datetime($value_proto);
108 0 return $dt;
109 }
110  
111 sub looks_like_a_date {
112 0 ▶ my ($self, $value) = @_;
Subroutine looks_like_a_date: not called CC=1 SCAR=6.9
Pod undocumented
113 0 my $dt = $self->parse_if_needed($value);
114 0 return $dt;
115 }
116  
117 sub is_future {
118 0 ▶ my ($self, $value) = @_;
Subroutine is_future: not called CC=1 SCAR=6.9
Pod documented
119 0 my $dt = $self->parse_if_needed($value);
120 0 return $dt > $self->_datetime->today;
121 }
122  
123 sub is_past {
124 0 ▶ my ($self, $value) = @_;
Subroutine is_past: not called CC=1 SCAR=6.9
Pod documented
125 0 my $dt = $self->parse_if_needed($value);
126 0 return $dt < $self->_datetime->today;
127 }
128  
129 50 ▶sub now { shift->_datetime->now }
Subroutine now: called CC=1 SCAR=0.0
Pod documented
130  
131 0 ▶sub today { shift->_datetime->today }
Subroutine today: not called CC=1 SCAR=6.9
Pod documented
132  
133 sub datetime {
134 8 ▶ my($self, %args) = @_;
Subroutine datetime: called CC=2 SCAR=7.6
Pod documented
135 8 ▶ $args{time_zone} ||= $self->tz;
Condition33%1/3
$args{"time_zone"} ||= $self->tz
l!l&&r!l&&!r
080
MC/DC0%0/2
$args{"time_zone"} ||= $self->tz
$args{"time_zone"} $self->tz
Truth table33%1/3
A ||= B
A= $args{"time_zone"}B= $self->tz
ABresult
1X1
011
000
136 8 return DateTime->new(%args);
137 }
138  
139 sub _datetime {
140 95 ▶ my($self) = @_;
Subroutine _datetime: called CC=1 SCAR=0.0
141 95 return 'DateTime';
142 }
143  
144 sub years_ago {
145 45 ▶ my($self, $years) = @_;
Subroutine years_ago: called CC=1 SCAR=0.0
Pod documented
146 45 return $self->_datetime->now->subtract(years => $years);
147 }
148  
149 sub years_from_now {
150 0 ▶ my($self, $years) = @_;
Subroutine years_from_now: not called CC=1 SCAR=6.9
Pod documented
151 0 return $self->_datetime->now->add(years => $years);
152 }
153  
154 7 1;
155  
156 =head1 NAME
157  
158 Valiant::Validator::Date - Verify that a value is is a standard Date (YYY-MM-DD)
159  
160 =head1 SYNOPSIS
161  
162 package Local::Test::Date;
163  
164 use Moo;
165 use Valiant::Validations;
166  
167 has birthday => (is=>'ro');
168  
169 validates birthday => (
170 date => {
171 min => sub { pop->years_ago(120) }, # Oldest person I think...
172 max => sub { pop->now },
173 }
174 );
175  
176 my $object = Local::Test::Date->new(birthday=>'2100-01-01');
177 $object->validate;
178  
179 warn $object->errors->_dump;
180  
181 $VAR1 = {
182 'birthday' => [
183 'chosen date can't be above {{max}}', # In real life {{max}} would be
184 # interpolated as DateTime->now
185 ]
186 };
187  
188 =head1 DESCRIPTION
189  
190 Validates a string pattern to make sure its in a standard date (YYYY-MM-DD) format,
191 which is commonly used in databases as a Date field and its also the canonical
192 pattern for the HTML5 input date type.
193  
194 Can accept a 'min' and 'max' attribute, which should be either a string in the
195 standard form or a M<DateTime> object.
196  
197 If you are using the Form helpers the max and min attributes can be reflected into
198 the date input type automatically.
199  
200 =head1 A NOTE ON TIMEZONES
201  
202 Please keep in mind that a lot of the shortcut helpers just call methods directly
203 on L<DateTime> which means they are using the system timezone. If you are working
204 with dates that are stored in a database you should be aware that the timezone
205 of the database and the timezone of the system running your code might not be the
206 same. This can lead to unexpected results. I don't have a lot of test cases
207 around this, please shout out your experiences if you run into issues. You can use
208 the C<tz> attribute (described below) to set the timezone of the L<DateTime> object
209 we create locally if needed
210  
211 =head1 ATTRIBUTES
212  
213 This validator supports the following attributes:
214  
215 =head2 tz
216  
217 Default is 'UTC'.
218  
219 If you are working with dates that are stored in a database you should be aware
220 that the timezone of the database and the timezone of the system running your code
221 might not be the same. This can lead to unexpected results. You can use the C<tz>
222 attribute to set the timezone of the L<DateTime> object we create locally if needed.
223  
224 =head2 pattern
225  
226 This is a string pattern that is used by L<DateTime::Format::Strptime> that your
227 date value must conform to (that is it must parse into a L<DateTime> object or the
228 validation fails). The default is '%Y-%m-%d'. This is a common database format and
229 is also used by HTML5 input date type fields.
230  
231 =head2 min
232  
233 If provided set a bottom limit on the allowed date. Either a string in YYYY-MM-DD
234 format or a L<DateTime> object.
235  
236 Value may also be a coderef so that you can set dynamic dates (such as always today)
237  
238 =head2 max
239  
240 If provided set an upper limit on the allowed date. Either a string in YYYY-MM-DD
241 format or a L<DateTime> object.
242  
243 Value may also be a coderef so that you can set dynamic dates (such as always today)
244  
245 =head2 min_eq
246  
247 If provided set a bottom limit on the allowed date. Either a string in YYYY-MM-DD
248 format or a L<DateTime> object. The date must be greater than or equal to this value.
249  
250 Value may also be a coderef so that you can set dynamic dates (such as always today)
251  
252 =head2 max_eq
253  
254 If provided set an upper limit on the allowed date. Either a string in YYYY-MM-DD
255 format or a L<DateTime> object. The date must be less than or equal to this value.
256  
257 Value may also be a coderef so that you can set dynamic dates (such as always today)
258  
259 =head2 cb
260  
261 A code reference that lets you create custom validation logic. This is basically the
262 same as the 'With' validator expect its only called IF the value is in valid date
263 format and you get that date inflated into a L<DateTime> object instead of the raw
264 string value. This makes it a little less work for you since you can skip those extra
265 checks. Also the coderef will receive the validator type instance as the third argument
266 so that you can take advantage of the type helpers (see below L<\HELPERS>).
267  
268 package MyRecord
269  
270 use Moo;
271 use Valiant::Validations;
272  
273 has attribute => (is=>'ro');
274  
275 validates attribute => (
276 date => +{
277 min => sub { pop->years_ago(10) },
278 max => sub { pop->now },
279 cb => \&my_special_method,
280 },
281 );
282  
283 sub my_special_method {
284 my ($self, $dt, $type) = @_;
285 # In this case $dt is a DateTime object inflated from the value
286 # of 'attribute'. This method won't get called if we previously
287 # determine that the value isn't in proper YYY-MM-DD format.
288  
289 # Custom validation stuff...
290 }
291  
292 =head2 below_min_msg
293  
294 =head2 above_max_msg
295  
296 =head2 below_min_eq_msg
297  
298 =head2 above_max_eq_msg
299  
300 =head2 invalid_date_msg
301  
302 The error message / tag associated with the given validation failures. Default messages
303 are provided.
304  
305 =head1 HELPERS
306  
307 This validator provides the following helpers. These basically just wrap L<DateTime>
308 and L<DateTime::Format::Strptime> so you can avoid having to create your own in your
309 record / object classes.
310  
311 =head2 datetime
312  
313 Returns a raw blessed L<DateTime> object. If you pass a hash of arguments, those will
314 be passed to C<new>.
315  
316 =head2 now
317  
318 returns L<DateTime> now.
319  
320 Please note that C<now> returns a L<DateTime> object that is both the current
321 date AND current time. In the context of a date validator this might be less
322 useful especially for comparisons since a date come out of a storage like a
323 DB will be at hour zero, where as C<now> will likely be after that.
324  
325 If you want just the current date you should use C<today>. In fact I'd say that
326 C<today> is the more useful of the two in the context of a date validator. I'm
327 leaving C<now> for back compatibility.
328  
329 =head2 today
330  
331 returns L<DateTime> today. This is the current date at hour zero. If you
332 are writing constraints like 'must be in the past' or 'must be in the future'
333 you probably want to use this method instead of C<now>.
334  
335 =head2 years_ago
336  
337 =head2 years_from_now
338  
339 Return a L<DateTime> object that is now plus or minus a given number of years.
340  
341 =head2 is_future
342  
343 =head2 is_past
344  
345 Given a L<DateTime> object (such as the value you are trying to validate), return true
346 or false if it is either in the future or in the past.
347  
348 =head1 SHORTCUT FORM
349  
350 This validator supports the follow shortcut forms:
351  
352 validates attribute => ( date => 1, ... );
353  
354 Which is the same as:
355  
356 validates attribute => (
357 date => +{ },
358 );
359  
360 Not many saved characters but makes usage syntactically regular across validators.
361  
362 You can also invoke a custom callback with a shortcut
363  
364 validates attribute => ( date => \&my_special_method, ... );
365  
366 sub my_special_method {
367 my ($self, $dt, $type) = @_;
368 # Custom validation stuff
369 }
370  
371 Which is the same as:
372  
373 validates attribute => (
374 date => +{
375 cb => \&my_special_method,
376 },
377 );
378  
379 Lastly you can specify that the date must be either future or past with a shortcut:
380  
381 validates attribute => ( date => 'is_future', ... );
382 validates attribute => ( date => 'is_past', ... );
383  
384 Which is the same as:
385  
386 validates attribute => (
387 date => +{
388 min => sub { pop->is_future },
389 max => sub { pop->is_past }
390 },
391 );
392  
393 =head1 GLOBAL PARAMETERS
394  
395 This validator supports all the standard shared parameters: C<if>, C<unless>,
396 C<message>, C<strict>, C<allow_undef>, C<allow_blank>.
397  
398 =head1 SEE ALSO
399
400 L<Valiant>, L<Valiant::Validator>, L<Valiant::Validator::Each>.
401  
402 =head1 AUTHOR
403
404 See L<Valiant>
405
406 =head1 COPYRIGHT & LICENSE
407
408 See L<Valiant>
409  
410 =cut
« Valiant/Naming.pm ↑ Summary Valiant/Util/Exception/MissingMethod.pm »