Builder.pm

filter: Statementstmt 97.4% 113 / 116 Branchbran 84.7% 39 / 46 Conditioncond 66.6% 12 / 18 MC/DCmcdc 33.3% 4 / 12 Subroutinesub 92.3% 24 / 26 Podpod 71.4% 10 / 14 totaltotal 87.0% 202 / 232 SCAR 34.6
CC
31
Cov
91%
create_constructor
7.0
create_class
6.0
parse_datetime
4.8
CRAP 31.7
« Builder/Parser.pm ↑ Summary Builder/Parser/generic.pm »
1 package DateTime::Format::Builder;
2  
3 23 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 23 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 23 our $VERSION = '0.82';
7  
8 23 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 23 ▶use DateTime 1.00;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 23 use Params::Validate 0.72 qw(
11 validate SCALAR ARRAYREF HASHREF SCALARREF CODEREF GLOB GLOBREF UNDEF
12 23 ▶);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 23 ▶use vars qw( %dispatch_data );
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 23 my $parser = 'DateTime::Format::Builder::Parser';
16  
17 sub verbose {
18 0 ▶ warn "Use of verbose() deprecated for the interim.";
Subroutine verbose: not called CC=1 SCAR=6.9
Pod undocumented
19 0 1;
20 }
21  
22 sub import {
23 36 ▶ my $class = shift;
Subroutine import: called CC=2 SCAR=6.9
24 36 ▶ $class->create_class( @_, class => (caller)[0] ) if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 13 23 36
25 }
26  
27 sub create_class {
28 21 ▶ my $class = shift;
Subroutine create_class: called CC=6 SCAR=17.9
Pod documented
29 21 my %args = validate(
30 @_,
31 {
32 class => { type => SCALAR, default => (caller)[0] },
33 version => { type => SCALAR, optional => 1 },
34 verbose => { type => SCALAR | GLOBREF | GLOB, optional => 1 },
35 parsers => { type => HASHREF },
36 groups => { type => HASHREF, optional => 1 },
37 constructor =>
38 { type => UNDEF | SCALAR | CODEREF, optional => 1 },
39 }
40 );
41  
42 21 ▶ verbose( $args{verbose} ) if exists $args{verbose};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"verbose"} 0 21 21
43  
44 21 my $target = $args{class}; # where we're writing our methods and such.
45  
46 # Create own lovely new package
47 {
48 23 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
49  
50 21 ▶ ${"${target}::VERSION"} = $args{version} if exists $args{version};
Branch: 1 branch
BranchTrueFalseTotal
if exists $args{"version"} 4 17 21
51  
52 $class->create_constructor(
53 $target, exists $args{constructor},
54 $args{constructor}
55 21 );
56  
57 # Turn groups of parser specs in to groups of parsers
58 {
59 19 my $specs = $args{groups};
60 19 my %groups;
61  
62 19 for my $label ( keys %$specs ) {
63 3 my $parsers = $specs->{$label};
64 3 my $code = $class->create_parser($parsers);
65 3 $groups{$label} = $code;
66 }
67  
68 19 $dispatch_data{$target} = \%groups;
69 }
70  
71 # Write all our parser methods, creating parsers as we go.
72 19 ▶ while ( my ( $method, $parsers ) = each %{ $args{parsers} } ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %{$args{"parsers"};}) 19 17 36
73 19 my $globname = $target . "::$method";
74 croak "Will not override a preexisting method $method()"
75 19 ▶ if defined &{$globname};
Branch: 1 branch
BranchTrueFalseTotal
if defined &{$globname;} 2 17 19
76 17 *$globname = $class->create_end_parser($parsers);
77 }
78 }
79  
80 }
81  
82 sub create_constructor {
83 21 ▶ shift;
Subroutine create_constructor: called CC=7 SCAR=19.5
Pod undocumented
84 21 my ( $target, $intended, $value ) = @_;
85  
86 21 my $new = $target . "::new";
87 21 ▶ $value = 1 unless $intended;
Branch: 1 branch
BranchTrueFalseTotal
unless $intended 13 8 21
88  
89 21 ▶ return unless $value;
Branch: 1 branch
BranchTrueFalseTotal
unless $value 3 18 21
90 18 ▶ return if not $intended and defined &$new;
Branch: 1 branch
BranchTrueFalseTotal
if not $intended and defined &$new 2 16 18
Condition100%3/3
not $intended and defined &$new
!ll&&!rl&&r
5112
MC/DC100%2/2
not $intended and defined &$new
not $intended defined &$new
Truth table100%3/3
not(A) and B
A= not $intendedB= defined &$new
ABresult
0X0
100
111
91 16 ▶ croak "Will not override a preexisting constructor new()"
Branch: 1 branch
BranchTrueFalseTotal
if defined &$new 2 14 16
92 if defined &$new;
93  
94 23 ▶ no strict 'refs';
Subroutine BEGIN: called CC=1 SCAR=0.0
95  
96 14 ▶ return *$new = $value if ref $value eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $value eq "CODE" 2 12 14
97 return *$new = sub {
98 16 ▶ my $class = shift;
Subroutine __ANON__: called CC=3 SCAR=11.0
99 16 ▶ croak "${class}->new takes no parameters." if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 1 15 16
100  
101 15 ▶ my $self = bless {}, ref($class) || $class;
Condition66%2/3
ref $class || $class
l!l&&r!l&&!r
1140
MC/DC0%0/2
ref $class || $class
ref $class $class
Truth table66%2/3
A || B
A= ref $classB= $class
ABresult
1X1
011
000
102  
103 # If called on an object, clone, but we've nothing to
104 # clone
105  
106 15 $self;
107 12 };
108 }
109  
110 sub create_parser {
111 42 ▶ my $class = shift;
Subroutine create_parser: called CC=4 SCAR=13.9
Pod undocumented
112 42 my @common = ( maker => $class );
113 42 ▶ if ( @_ == 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 1) { } 29 13 42
114 29 my $parsers = shift;
115 29 ▶ my @parsers = (
Branch: 2 branches
BranchTrueFalseTotal
ref $parsers eq 'HASH' ? : 7 22 29
ref $parsers eq 'ARRAY' ? : 22 0 22
116 ( ref $parsers eq 'HASH' )
117 ? %$parsers
118 : ( ( ref $parsers eq 'ARRAY' ) ? @$parsers : $parsers )
119 );
120 29 $parser->create_parser( \@common, @parsers );
121 }
122 else {
123 13 $parser->create_parser( \@common, @_ );
124 }
125 }
126  
127 # This creates the end methods. Coderefs die on bad parses, return C<DateTime>
128 # objects on good parse.
129 sub create_end_parser {
130 25 ▶ my ( $class, $parsers ) = @_;
Subroutine create_end_parser: called CC=1 SCAR=0.0
Pod undocumented
131 25 $class->create_method( $class->create_parser($parsers) );
132 }
133  
134 sub create_method {
135 25 ▶ shift;
Subroutine create_method: called CC=1 SCAR=0.0
Pod documented
136 25 my ($parser) = @_;
137  
138 return sub {
139 31 ▶ my $self = shift;
Subroutine __ANON__: called CC=1 SCAR=0.0
140 31 $parser->parse( $self, @_ );
141 25 };
142 }
143  
144 sub on_fail {
145 3 ▶ shift;
Subroutine on_fail: called CC=4 SCAR=13.9
Pod documented
146 3 my ($input) = @_;
147  
148 3 my $pkg;
149 3 my $i = 0;
150 3 ▶ while ( ($pkg) = caller( $i++ ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (($pkg) = caller $i++) 15 0 15
151 last
152 15 ▶ if ( !UNIVERSAL::isa( $pkg, 'DateTime::Format::Builder' )
Branch: 1 branch
BranchTrueFalseTotal
unless UNIVERSAL::isa($pkg, "DateTime::Format::Builder") or UNIVERSAL::isa($pkg, "DateTime::Format::Builder::Parser") 3 12 15
Condition100%3/3
UNIVERSAL::isa($pkg, "DateTime::Format::Builder") or UNIVERSAL::isa($pkg, "DateTime::Format::Builder::Parser")
l!l&&r!l&&!r
393
MC/DC100%2/2
UNIVERSAL::isa($pkg, "DateTime::Format::Builder") or UNIVERSAL::isa($pkg, "DateTime::Format::Builder::Parser")
UNIVERSAL::isa($pkg, "DateTime::Format::Builder") UNIVERSAL::isa($pkg, "DateTime::Format::Builder::Parser")
Truth table100%3/3
A or B
A= UNIVERSAL::isa($pkg, "DateTime::Format::Builder")B= UNIVERSAL::isa($pkg, "DateTime::Format::Builder::Parser")
ABresult
1X1
011
000
153 && !UNIVERSAL::isa( $pkg, 'DateTime::Format::Builder::Parser' ) );
154 }
155 3 local $Carp::CarpLevel = $i;
156 3 croak "Invalid date format: $input";
157 }
158  
159 sub new {
160 13 ▶ my $class = shift;
Subroutine new: called CC=4 SCAR=13.9
Pod documented
161 13 ▶ croak "Constructor 'new' takes no parameters" if @_;
Branch: 1 branch
BranchTrueFalseTotal
if @_ 1 12 13
162 my $self = bless {
163 1 ▶ parser => sub { croak "No parser set." }
Subroutine __ANON__: called CC=1 SCAR=0.0
164 },
165 12 ▶ ref($class) || $class;
Condition66%2/3
ref $class || $class
l!l&&r!l&&!r
2100
MC/DC0%0/2
ref $class || $class
ref $class $class
Truth table66%2/3
A || B
A= ref $classB= $class
ABresult
1X1
011
000
166 12 ▶ if ( ref $class ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $class) 2 10 12
167  
168 # If called on an object, clone
169 2 $self->set_parser( $class->get_parser );
170  
171 # and that's it. we don't store that much info per object
172 }
173 12 return $self;
174 }
175  
176 sub parser {
177 8 ▶ my $class = shift;
Subroutine parser: called CC=2 SCAR=6.9
Pod documented
178 8 my $parser = $class->create_end_parser( \@_ );
179  
180 # Do we need to instantiate a new object for return,
181 # or are we modifying an existing object?
182 8 my $self;
183 8 ▶ $self = ref $class ? $class : $class->new();
Branch: 1 branch
BranchTrueFalseTotal
ref $class ? : 2 6 8
184  
185 8 $self->set_parser($parser);
186  
187 8 $self;
188 }
189  
190 sub clone {
191 1 ▶ my $self = shift;
Subroutine clone: called CC=2 SCAR=7.1
Pod documented
192 1 ▶ croak "Calling object method as class method!" unless ref $self;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $self 0 1 1
193 1 return $self->new();
194 }
195  
196 sub set_parser {
197 10 ▶ my ( $self, $parser ) = @_;
Subroutine set_parser: called CC=3 SCAR=12.0
Pod documented
198 10 ▶ croak "set_parser given something other than a coderef"
Branch: 1 branch
BranchTrueFalseTotal
unless $parser and ref $parser eq "CODE" 0 10 10
Condition33%1/3
$parser and ref $parser eq "CODE"
!ll&&!rl&&r
0010
MC/DC0%0/2
$parser and ref $parser eq "CODE"
$parser ref $parser eq "CODE"
Truth table33%1/3
A and B
A= $parserB= ref $parser eq "CODE"
ABresult
0X0
100
111
199 unless $parser
200 and ref $parser eq 'CODE';
201 10 $self->{parser} = $parser;
202 10 $self;
203 }
204  
205 sub get_parser {
206 6 ▶ my ($self) = @_;
Subroutine get_parser: called CC=1 SCAR=0.0
Pod documented
207 6 return $self->{parser};
208 }
209  
210 sub parse_datetime {
211 14 ▶ my $self = shift;
Subroutine parse_datetime: called CC=4 SCAR=15.6
Pod documented
212 14 ▶ croak "parse_datetime is an object method, not a class method."
Branch: 1 branch
BranchTrueFalseTotal
unless ref $self and $self->isa(__PACKAGE__) 0 14 14
Condition33%1/3
ref $self and $self->isa(__PACKAGE__)
!ll&&!rl&&r
0014
MC/DC0%0/2
ref $self and $self->isa(__PACKAGE__)
ref $self $self->isa(__PACKAGE__)
Truth table33%1/3
A and B
A= ref $selfB= $self->isa(__PACKAGE__)
ABresult
0X0
100
111
213 unless ref $self and $self->isa(__PACKAGE__);
214 14 ▶ croak "No date specified." unless @_;
Branch: 1 branch
BranchTrueFalseTotal
unless @_ 0 14 14
215 14 return $self->{parser}->( $self, @_ );
216 }
217  
218 sub format_datetime {
219 0 ▶ croak __PACKAGE__ . "::format_datetime not implemented.";
Subroutine format_datetime: not called CC=1 SCAR=6.9
Pod documented
220 }
221  
222 23 require DateTime::Format::Builder::Parser;
223  
224 23 1;
225  
226 # ABSTRACT: Create DateTime parser classes and objects.
227  
228 __END__
229  
230 =pod
231  
232 =encoding UTF-8
233  
234 =head1 NAME
235  
236 DateTime::Format::Builder - Create DateTime parser classes and objects.
237  
238 =head1 VERSION
239  
240 version 0.82
241  
242 =head1 SYNOPSIS
243  
244 package DateTime::Format::Brief;
245  
246 use DateTime::Format::Builder
247 (
248 parsers => {
249 parse_datetime => [
250 {
251 regex => qr/^(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)$/,
252 params => [qw( year month day hour minute second )],
253 },
254 {
255 regex => qr/^(\d{4})(\d\d)(\d\d)$/,
256 params => [qw( year month day )],
257 },
258 ],
259 }
260 );
261  
262 =head1 DESCRIPTION
263  
264 DateTime::Format::Builder creates DateTime parsers.
265 Many string formats of dates and times are simple and just
266 require a basic regular expression to extract the relevant
267 information. Builder provides a simple way to do this
268 without writing reams of structural code.
269  
270 Builder provides a number of methods, most of which you'll
271 never need, or at least rarely need. They're provided more
272 for exposing of the module's innards to any subclasses, or
273 for when you need to do something slightly beyond what I
274 expected.
275  
276 =head1 TUTORIAL
277  
278 See L<DateTime::Format::Builder::Tutorial>.
279  
280 =head1 ERROR HANDLING AND BAD PARSES
281  
282 Often, I will speak of C<undef> being returned, however
283 that's not strictly true.
284  
285 When a simple single specification is given for a method,
286 the method isn't given a single parser directly. It's given
287 a wrapper that will call C<on_fail()> if the single parser
288 returns C<undef>. The single parser must return C<undef> so
289 that a multiple parser can work nicely and actual errors can
290 be thrown from any of the callbacks.
291  
292 Similarly, any multiple parsers will only call C<on_fail()>
293 right at the end when it's tried all it could.
294  
295 C<on_fail()> (see L<later|/on_fail>) is defined, by default,
296 to throw an error.
297  
298 Multiple parser specifications can also specify C<on_fail>
299 with a coderef as an argument in the options block. This
300 will take precedence over the inheritable and overrideable
301 method.
302  
303 That said, don't throw real errors from callbacks in
304 multiple parser specifications unless you really want
305 parsing to stop right there and not try any other parsers.
306  
307 In summary: calling a B<method> will result in either a
308 C<DateTime> object being returned or an error being thrown
309 (unless you've overridden C<on_fail()> or
310 C<create_method()>, or you've specified a C<on_fail> key to
311 a multiple parser specification).
312  
313 Individual B<parsers> (be they multiple parsers or single
314 parsers) will return either the C<DateTime> object or
315 C<undef>.
316  
317 =head1 SINGLE SPECIFICATIONS
318  
319 A single specification is a hash ref of instructions
320 on how to create a parser.
321  
322 The precise set of keys and values varies according to parser
323 type. There are some common ones though:
324  
325 =over 4
326  
327 =item *
328  
329 B<length> is an optional parameter that can be used to
330 specify that this particular I<regex> is only applicable to
331 strings of a certain fixed length. This can be used to make
332 parsers more efficient. It's strongly recommended that any
333 parser that can use this parameter does.
334  
335 You may happily specify the same length twice. The parsers
336 will be tried in order of specification.
337  
338 You can also specify multiple lengths by giving it an
339 arrayref of numbers rather than just a single scalar.
340 If doing so, please keep the number of lengths to a minimum.
341  
342 If any specifications without I<length>s are given and the
343 particular I<length> parser fails, then the non-I<length>
344 parsers are tried.
345  
346 This parameter is ignored unless the specification is part
347 of a multiple parser specification.
348  
349 =item *
350  
351 B<label> provides a name for the specification and is passed
352 to some of the callbacks about to mentioned.
353  
354 =item *
355  
356 B<on_match> and B<on_fail> are callbacks. Both routines will
357 be called with parameters of:
358  
359 =over 4
360  
361 =item *
362  
363 B<input>, being the input to the parser (after any
364 preprocessing callbacks).
365  
366 =item *
367  
368 B<label>, being the label of the parser, if there is one.
369  
370 =item *
371  
372 B<self>, being the object on which the method has been
373 invoked (which may just be a class name). Naturally, you
374 can then invoke your own methods on it do get information
375 you want.
376  
377 =item *
378  
379 B<args>, being an arrayref of any passed arguments, if any.
380 If there were no arguments, then this parameter is not given.
381  
382 =back
383  
384 These routines will be called depending on whether the
385 B<regex> match succeeded or failed.
386  
387 =item *
388  
389 B<preprocess> is a callback provided for cleaning up input
390 prior to parsing. It's given a hash as arguments with the
391 following keys:
392  
393 =over 4
394  
395 =item *
396  
397 B<input> being the datetime string the parser was given (if
398 using multiple specifications and an overall I<preprocess>
399 then this is the date after it's been through that
400 preprocessor).
401  
402 =item *
403  
404 B<parsed> being the state of parsing so far. Usually empty
405 at this point unless an overall I<preprocess> was given.
406 Items may be placed in it and will be given to any
407 B<postprocess>or and C<< DateTime->new >> (unless the
408 postprocessor deletes it).
409  
410 =item *
411  
412 B<self>, B<args>, B<label> as per I<on_match> and I<on_fail>.
413  
414 =back
415  
416 The return value from the routine is what is given to the
417 I<regex>. Note that this is last code stop before the match.
418  
419 B<Note>: mixing I<length> and a I<preprocess> that modifies
420 the length of the input string is probably not what you
421 meant to do. You probably meant to use the
422 I<multiple parser> variant of I<preprocess> which is done
423 B<before> any length calculations. This C<single parser> variant
424 of I<preprocess> is performed B<after> any length
425 calculations.
426  
427 =item *
428  
429 B<postprocess> is the last code stop before
430 C<< DateTime->new() >> is called. It's given the same
431 arguments as I<preprocess>. This allows it to modify the
432 parsed parameters after the parse and before the creation
433 of the object. For example, you might use:
434  
435 {
436 regex => qr/^(\d\d) (\d\d) (\d\d)$/,
437 params => [qw( year month day )],
438 postprocess => \&_fix_year,
439 }
440  
441 where C<_fix_year> is defined as:
442  
443 sub _fix_year
444 {
445 my %args = @_;
446 my ($date, $p) = @args{qw( input parsed )};
447 $p->{year} += $p->{year} > 69 ? 1900 : 2000;
448 return 1;
449 }
450  
451 This will cause the two digit years to be corrected
452 according to the cut off. If the year was '69' or lower,
453 then it is made into 2069 (or 2045, or whatever the year was
454 parsed as). Otherwise it is assumed to be 19xx. The
455 L<DateTime::Format::Mail> module uses code similar to this
456 (only it allows the cut off to be configured and it doesn't
457 use Builder).
458  
459 B<Note>: It is B<very important> to return an explicit value
460 from the I<postprocess> callback. If the return value is
461 false then the parse is taken to have failed. If the return
462 value is true, then the parse is taken to have succeeded and
463 C<< DateTime->new() >> is called.
464  
465 =back
466  
467 See the documentation for the individual parsers for their
468 valid keys.
469  
470 Parsers at the time of writing are:
471  
472 =over 4
473  
474 =item *
475  
476 L<DateTime::Format::Builder::Parser::Regex> - provides regular
477 expression based parsing.
478  
479 =item *
480  
481 L<DateTime::Format::Builder::Parser::Strptime> - provides strptime
482 based parsing.
483  
484 =back
485  
486 =head2 Subroutines / coderefs as specifications.
487  
488 A single parser specification can be a coderef. This was
489 added mostly because it could be and because I knew someone,
490 somewhere, would want to use it.
491  
492 If the specification is a reference to a piece of code, be
493 it a subroutine, anonymous, or whatever, then it's passed
494 more or less straight through. The code should return
495 C<undef> in event of failure (or any false value,
496 but C<undef> is strongly preferred), or a true value in the
497 event of success (ideally a C<DateTime> object or some
498 object that has the same interface).
499  
500 This all said, I generally wouldn't recommend using this
501 feature unless you have to.
502  
503 =head2 Callbacks
504  
505 I mention a number of callbacks in this document.
506  
507 Any time you see a callback being mentioned, you can,
508 if you like, substitute an arrayref of coderefs rather
509 than having the straight coderef.
510  
511 =head1 MULTIPLE SPECIFICATIONS
512  
513 These are very easily described as an array of single
514 specifications.
515  
516 Note that if the first element of the array is an arrayref,
517 then you're specifying options.
518  
519 =over 4
520  
521 =item *
522  
523 B<preprocess> lets you specify a preprocessor that is called
524 before any of the parsers are tried. This lets you do things
525 like strip off timezones or any unnecessary data. The most
526 common use people have for it at present is to get the input
527 date to a particular length so that the I<length> is usable
528 (L<DateTime::Format::ICal> would use it to strip off the
529 variable length timezone).
530  
531 Arguments are as for the I<single parser> I<preprocess>
532 variant with the exception that I<label> is never given.
533  
534 =item *
535  
536 B<on_fail> should be a reference to a subroutine that is
537 called if the parser fails. If this is not provided, the
538 default action is to call
539 C<DateTime::Format::Builder::on_fail>, or the C<on_fail>
540 method of the subclass of DTFB that was used to create the
541 parser.
542  
543 =back
544  
545 =head1 EXECUTION FLOW
546  
547 Builder allows you to plug in a fair few callbacks, which
548 can make following how a parse failed (or succeeded
549 unexpectedly) somewhat tricky.
550  
551 =head2 For Single Specifications
552  
553 A single specification will do the following:
554  
555 User calls parser:
556  
557 my $dt = $class->parse_datetime( $string );
558  
559 =over 4
560  
561 =item 1
562  
563 I<preprocess> is called. It's given C<$string> and a
564 reference to the parsing workspace hash, which we'll call
565 C<$p>. At this point, C<$p> is empty. The return value is
566 used as C<$date> for the rest of this single parser.
567 Anything put in C<$p> is also used for the rest of this
568 single parser.
569  
570 =item 2
571  
572 I<regex> is applied.
573  
574 =item 3
575  
576 If I<regex> B<did not> match, then I<on_fail> is called (and is given
577 C<$date> and also I<label> if it was defined). Any return
578 value is ignored and the next thing is for the single
579 parser to return C<undef>.
580  
581 If I<regex> B<did> match, then I<on_match> is called with
582 the same arguments as would be given to I<on_fail>. The
583 return value is similarly ignored, but we then move to step
584 4 rather than exiting the parser.
585  
586 =item 4
587  
588 I<postprocess> is called with C<$date> and a filled out
589 C<$p>. The return value is taken as a indication of whether
590 the parse was a success or not. If it wasn't a success then
591 the single parser will exit at this point, returning undef.
592  
593 =item 5
594  
595 C<< DateTime->new() >> is called and the user is given the
596 resultant C<DateTime> object.
597  
598 =back
599  
600 See the section on L<error handling|/"ERROR HANDLING AND BAD PARSES">
601 regarding the C<undef>s mentioned above.
602  
603 =head2 For Multiple Specifications
604  
605 With multiple specifications:
606  
607 User calls parser:
608  
609 my $dt = $class->complex_parse( $string );
610  
611 =over 4
612  
613 =item 1
614  
615 The overall I<preprocess>or is called and is given C<$string>
616 and the hashref C<$p> (identically to the per parser
617 I<preprocess> mentioned in the previous flow).
618  
619 If the callback modifies C<$p> then a B<copy> of C<$p> is
620 given to each of the individual parsers. This is so parsers
621 won't accidentally pollute each other's workspace.
622  
623 =item 2
624  
625 If an appropriate length specific parser is found, then it
626 is called and the single parser flow (see the previous
627 section) is followed, and the parser is given a copy of
628 C<$p> and the return value of the overall I<preprocess>or as
629 C<$date>.
630  
631 If a C<DateTime> object was returned so we go straight back
632 to the user.
633  
634 If no appropriate parser was found, or the parser returned
635 C<undef>, then we progress to step 3!
636  
637 =item 3
638  
639 Any non-I<length> based parsers are tried in the order they
640 were specified.
641  
642 For each of those the single specification flow above is
643 performed, and is given a copy of the output from the
644 overall preprocessor.
645  
646 If a real C<DateTime> object is returned then we exit back
647 to the user.
648  
649 If no parser could parse, then an error is thrown.
650  
651 =back
652  
653 See the section on L<error handling|/ERROR HANDLING AND BAD PARSES>
654 regarding the C<undef>s mentioned above.
655  
656 =head1 METHODS
657  
658 In the general course of things you won't need any of the
659 methods. Life often throws unexpected things at us so the
660 methods are all available for use.
661  
662 =head2 import
663  
664 C<import()> is a wrapper for C<create_class()>. If you
665 specify the I<class> option (see documentation for
666 C<create_class()>) it will be ignored.
667  
668 =head2 create_class
669  
670 This method can be used as the runtime equivalent of
671 C<import()>. That is, it takes the exact same parameters as
672 when one does:
673  
674 use DateTime::Format::Builder ( blah blah blah )
675  
676 That can be (almost) equivalently written as:
677  
678 use DateTime::Format::Builder;
679 DateTime::Format::Builder->create_class( blah blah blah );
680  
681 The difference being that the first is done at compile time
682 while the second is done at run time.
683  
684 In the tutorial I said there were only two parameters at
685 present. I lied. There are actually three of them.
686  
687 =over 4
688  
689 =item *
690  
691 B<parsers> takes a hashref of methods and their parser
692 specifications. See the
693 L<DateTime::Format::Builder::Tutorial> for details.
694  
695 Note that if you define a subroutine of the same name as one
696 of the methods you define here, an error will be thrown.
697  
698 =item *
699  
700 B<constructor> determines whether and how to create a
701 C<new()> function in the new class. If given a true value, a
702 constructor is created. If given a false value, one isn't.
703  
704 If given an anonymous sub or a reference to a sub then that
705 is used as C<new()>.
706  
707 The default is C<1> (that is, create a constructor using
708 our default code which simply creates a hashref and blesses
709 it).
710  
711 If your class defines its own C<new()> method it will not be
712 overwritten. If you define your own C<new()> and B<also> tell
713 Builder to define one an error will be thrown.
714  
715 =item *
716  
717 B<verbose> takes a value. If the value is undef, then
718 logging is disabled. If the value is a filehandle then
719 that's where logging will go. If it's a true value, then
720 output will go to C<STDERR>.
721  
722 Alternatively, call C<$DateTime::Format::Builder::verbose()>
723 with the relevant value. Whichever value is given more
724 recently is adhered to.
725  
726 Be aware that verbosity is a global wide setting.
727  
728 =item *
729  
730 B<class> is optional and specifies the name of the class in
731 which to create the specified methods.
732  
733 If using this method in the guise of C<import()> then this
734 field will cause an error so it is only of use when calling
735 as C<create_class()>.
736  
737 =item *
738  
739 B<version> is also optional and specifies the value to give
740 C<$VERSION> in the class. It's generally not recommended
741 unless you're combining with the I<class> option. A
742 C<ExtUtils::MakeMaker> / C<CPAN> compliant version
743 specification is much better.
744  
745 =back
746  
747 In addition to creating any of the methods it also creates a
748 C<new()> method that can instantiate (or clone) objects.
749  
750 =head1 SUBCLASSING
751  
752 In the rest of the documentation I've often lied in order to
753 get some of the ideas across more easily. The thing is, this
754 module's very flexible. You can get markedly different
755 behaviour from simply subclassing it and overriding some
756 methods.
757  
758 =head2 create_method
759  
760 Given a parser coderef, returns a coderef that is suitable
761 to be a method.
762  
763 The default action is to call C<on_fail()> in the event of a
764 non-parse, but you can make it do whatever you want.
765  
766 =head2 on_fail
767  
768 This is called in the event of a non-parse (unless you've
769 overridden C<create_method()> to do something else.
770  
771 The single argument is the input string. The default action
772 is to call C<croak()>. Above, where I've said parsers or
773 methods throw errors, this is the method that is doing the
774 error throwing.
775  
776 You could conceivably override this method to, say, return
777 C<undef>.
778  
779 =head1 USING BUILDER OBJECTS aka USERS USING BUILDER
780  
781 The methods listed in the L<METHODS> section are all you
782 generally need when creating your own class. Sometimes
783 you may not want a full blown class to parse something just
784 for this one program. Some methods are provided to make that
785 task easier.
786  
787 =head2 new
788  
789 The basic constructor. It takes no arguments, merely returns
790 a new C<DateTime::Format::Builder> object.
791  
792 my $parser = DateTime::Format::Builder->new();
793  
794 If called as a method on an object (rather than as a class
795 method), then it clones the object.
796  
797 my $clone = $parser->new();
798  
799 =head2 clone
800  
801 Provided for those who prefer an explicit C<clone()> method
802 rather than using C<new()> as an object method.
803  
804 my $clone_of_clone = $clone->clone();
805  
806 =head2 parser
807  
808 Given either a single or multiple parser specification, sets
809 the object to have a parser based on that specification.
810  
811 $parser->parser(
812 regex => qr/^ (\d{4}) (\d\d) (\d\d) $/x;
813 params => [qw( year month day )],
814 );
815  
816 The arguments given to C<parser()> are handed directly to
817 C<create_parser()>. The resultant parser is passed to
818 C<set_parser()>.
819  
820 If called as an object method, it returns the object.
821  
822 If called as a class method, it creates a new object, sets
823 its parser and returns that object.
824  
825 =head2 set_parser
826  
827 Sets the parser of the object to the given parser.
828  
829 $parser->set_parser( $coderef );
830  
831 Note: this method does not take specifications. It also does
832 not take anything except coderefs. Luckily, coderefs are
833 what most of the other methods produce.
834  
835 The method return value is the object itself.
836  
837 =head2 get_parser
838  
839 Returns the parser the object is using.
840  
841 my $code = $parser->get_parser();
842  
843 =head2 parse_datetime
844  
845 Given a string, it calls the parser and returns the
846 C<DateTime> object that results.
847  
848 my $dt = $parser->parse_datetime( "1979 07 16" );
849  
850 The return value, if not a C<DateTime> object, is whatever
851 the parser wants to return. Generally this means that if the
852 parse failed an error will be thrown.
853  
854 =head2 format_datetime
855  
856 If you call this function, it will throw an error.
857  
858 =head1 LONGER EXAMPLES
859  
860 Some longer examples are provided in the distribution. These
861 implement some of the common parsing DateTime modules using
862 Builder. Each of them are, or were, drop in replacements for
863 the modules at the time of writing them.
864  
865 =head1 THANKS
866  
867 Dave Rolsky (DROLSKY) for kickstarting the DateTime project, writing
868 L<DateTime::Format::ICal> and L<DateTime::Format::MySQL>, and some much needed
869 review.
870  
871 Joshua Hoblitt (JHOBLITT) for the concept, some of the API, impetus for
872 writing the multi-length code (both one length with multiple parsers and
873 single parser with multiple lengths), blame for the Regex custom constructor
874 code, spotting a bug in Dispatch, and more much needed review.
875  
876 Kellan Elliott-McCrea (KELLAN) for even more review, suggestions,
877 L<DateTime::Format::W3CDTF> and the encouragement to rewrite these docs almost
878 100%!
879  
880 Claus Färber (CFAERBER) for having me get around to fixing the
881 auto-constructor writing, providing the 'args'/'self' patch, and suggesting
882 the multi-callbacks.
883  
884 Rick Measham (RICKM) for L<DateTime::Format::Strptime> which Builder now
885 supports.
886  
887 Matthew McGillis for pointing out that C<on_fail> overriding should be
888 simpler.
889  
890 Simon Cozens (SIMON) for saying it was cool.
891  
892 =head1 SEE ALSO
893  
894 C<datetime@perl.org> mailing list.
895  
896 http://datetime.perl.org/
897  
898 L<perl>, L<DateTime>, L<DateTime::Format::Builder::Tutorial>,
899 L<DateTime::Format::Builder::Parser>
900  
901 =head1 SUPPORT
902  
903 Bugs may be submitted at L<http://rt.cpan.org/Public/Dist/Display.html?Name=DateTime-Format-Builder> or via email to L<bug-datetime-format-builder@rt.cpan.org|mailto:bug-datetime-format-builder@rt.cpan.org>.
904  
905 I am also usually active on IRC as 'autarch' on C<irc://irc.perl.org>.
906  
907 =head1 SOURCE
908  
909 The source code repository for DateTime-Format-Builder can be found at L<https://github.com/houseabsolute/DateTime-Format-Builder>.
910  
911 =head1 DONATIONS
912  
913 If you'd like to thank me for the work I've done on this module, please
914 consider making a "donation" to me via PayPal. I spend a lot of free time
915 creating free software, and would appreciate any support you'd care to offer.
916  
917 Please note that B<I am not suggesting that you must do this> in order for me
918 to continue working on this particular software. I will continue to do so,
919 inasmuch as I have in the past, for as long as it interests me.
920  
921 Similarly, a donation made in this way will probably not make me work on this
922 software much more, unless I get so many donations that I can consider working
923 on free software full time (let's all have a chuckle at that together).
924  
925 To donate, log into PayPal and send money to autarch@urth.org, or use the
926 button at L<http://www.urth.org/~autarch/fs-donation.html>.
927  
928 =head1 AUTHORS
929  
930 =over 4
931  
932 =item *
933  
934 Dave Rolsky <autarch@urth.org>
935  
936 =item *
937  
938 Iain Truskett
939  
940 =back
941  
942 =head1 CONTRIBUTORS
943  
944 =for stopwords Daisuke Maki Ian Truskett (no author)
945  
946 =over 4
947  
948 =item *
949  
950 Daisuke Maki <daisuke@endeworks.jp>
951  
952 =item *
953  
954 Ian Truskett <spoon@cpan.org>
955  
956 =item *
957  
958 (no author) <(no author)@49043108-e40d-0410-ab17-85caa8b5b18d>
959  
960 =back
961  
962 =head1 COPYRIGHT AND LICENSE
963  
964 This software is Copyright (c) 2019 by Dave Rolsky.
965  
966 This is free software, licensed under:
967  
968 The Artistic License 2.0 (GPL Compatible)
969  
970 The full text of the license can be found in the
971 F<LICENSE> file included with this distribution.
972  
973 =cut
« Builder/Parser.pm ↑ Summary Builder/Parser/generic.pm »