/[webpac2]/trunk/lib/WebPAC/Validate.pm
This is repository of my old source code which isn't updated any more. Go to git.rot13.org for current projects!
ViewVC logotype

Contents of /trunk/lib/WebPAC/Validate.pm

Parent Directory Parent Directory | Revision Log Revision Log


Revision 852 - (show annotations)
Sun May 27 11:27:12 2007 UTC (16 years, 11 months ago) by dpavlin
File size: 12142 byte(s)
 r1261@llin:  dpavlin | 2007-05-27 13:27:55 +0200
 profiling: add sub { dump( ) } for $log->debug

1 package WebPAC::Validate;
2
3 use warnings;
4 use strict;
5
6 use blib;
7
8 use base 'WebPAC::Common';
9 use File::Slurp;
10 use List::Util qw/first/;
11 use Data::Dump qw/dump/;
12 use WebPAC::Normalize qw/_pack_subfields_hash/;
13 use Storable qw/dclone/;
14
15 =head1 NAME
16
17 WebPAC::Validate - provide simple validation for records
18
19 =head1 VERSION
20
21 Version 0.12
22
23 =cut
24
25 our $VERSION = '0.12';
26
27 =head1 SYNOPSIS
28
29 This module provide a simple way to validate your file against a simple
30 configuration file in following format:
31
32 # field 10 doesn't have any subfields
33 10
34 # same with 101
35 101
36 # field 200 have valid subfields a-g
37 # and field e is repeatable
38 200 a b c d e* f g
39 # field 205 can have only subfield a
40 # and must exists
41 205! a
42 # while 210 can have a c or d
43 210 a c d
44 # field which is ignored in validation
45 999-
46
47 =head1 FUNCTIONS
48
49 =head2 new
50
51 Create new validation object
52
53 my $validate = new WebPAC::Validate(
54 path => 'conf/validate/file',
55 delimiters => [ ' : ', ' / ', ' ; ', ' , ' ],
56 delimiters_path => 'conf/validate/delimiters/file',
57 );
58
59 Optional parametar C<delimiters> will turn on validating of delimiters. Be
60 careful here, those delimiters are just stuck into regex, so they can
61 contain L<perlre> regexpes.
62
63 =cut
64
65 sub new {
66 my $class = shift;
67 my $self = {@_};
68 bless($self, $class);
69
70 my $log = $self->_get_logger();
71
72 $log->logdie("need path or delimiters_path") unless ( $self->{path} || $self->{delimiters_path} );
73
74 if ( $self->{path} ) {
75
76 my $v_file = read_file( $self->{path} ) ||
77 $log->logdie("can't open validate path $self->{path}: $!");
78
79 my $v;
80 my $curr_line = 1;
81
82 foreach my $l (split(/[\n\r]+/, $v_file)) {
83 $curr_line++;
84
85 # skip comments and whitespaces
86 next if ($l =~ /^#/ || $l =~ /^\s*$/);
87
88 $l =~ s/^\s+//;
89 $l =~ s/\s+$//;
90
91 my @d = split(/\s+/, $l);
92
93 my $fld = shift @d;
94
95 if ($fld =~ s/!$//) {
96 $self->{must_exist}->{$fld}++;
97 } elsif ($fld =~ s/-$//) {
98 $self->{dont_validate}->{$fld}++;
99 }
100
101 $log->logdie("need field name in line $curr_line: $l") unless (defined($fld));
102
103 if (@d) {
104 $v->{$fld} = [ map {
105 my $sf = $_;
106 if ( $sf =~ s/!(\*)?$/$1/ ) {
107 $self->{must_exist_sf}->{ $fld }->{ $sf }++;
108 };
109 $sf;
110 } @d ];
111 } else {
112 $v->{$fld} = 1;
113 }
114
115 }
116
117 $log->debug("current validation rules: ", dump($v));
118
119 $self->{rules} = $v;
120
121 $log->info("validation uses rules from $self->{path}");
122 }
123
124 if ( $self->{delimiters} ) {
125 $self->{delimiters_regex} = '(\^[a-z0-9]|' . join('|', @{ $self->{delimiters} }) . ')';
126 $log->info("validation check delimiters with regex $self->{delimiters_regex}");
127 }
128
129 if ( my $path = $self->{delimiters_path} ) {
130 if ( -e $path ) {
131 $log->info("using delimiter validation rules from $path");
132 open(my $d, $path) || $log->fatal("can't open $path: $!");
133 while(<$d>) {
134 chomp($d);
135 if (/^\s*(#*)\s*(\d+)\t+(\d+)\t+(.*)$/) {
136 my ($comment,$field,$count,$template) = ($1,$2,$3,$4);
137 $self->{_validate_delimiters_templates}->{$field}->{$template} = $count unless ($comment);
138 } else {
139 warn "## ignored $d\n";
140 }
141 }
142 close($d);
143 #warn "_validate_delimiters_templates = ",dump( $self->{_validate_delimiters_templates} );
144 } else {
145 $log->warn("delimiters path $path doesn't exist, it will be created after this run");
146 }
147 }
148
149 $self ? return $self : return undef;
150 }
151
152 =head2 validate_rec
153
154 Validate record and return errors
155
156 my @errors = $validate->validate_rec( $rec, $rec_dump );
157
158 =cut
159
160 sub validate_rec {
161 my $self = shift;
162
163 my $log = $self->_get_logger();
164
165 my $rec = shift || $log->logdie("validate_rec need record");
166 my $rec_dump = shift;
167
168 $log->logdie("rec isn't HASH") unless (ref($rec) eq 'HASH');
169 # $log->logdie("can't find validation rules") unless (my $r = $self->{rules});
170 my $r = $self->{rules};
171
172 my $errors;
173
174 $log->debug("rec = ", sub { dump($rec) }, "keys = ", keys %{ $rec });
175
176 my $fields;
177
178 foreach my $f (keys %{ $rec }) {
179
180 next if (!defined($f) || $f eq '' || $f eq '000');
181
182 # first check delimiters
183 if ( my $regex = $self->{delimiters_regex} ) {
184
185 foreach my $v (@{ $rec->{$f} }) {
186 my $l = _pack_subfields_hash( $v, 1 );
187 my $subfield_dump = $l;
188 my $template = '';
189 $l =~ s/$regex/$template.=$1/eg;
190 #warn "## template: $template\n";
191
192 if ( $template ) {
193 $self->{_delimiters_templates}->{$f}->{$template}++;
194
195 if ( my $v = $self->{_validate_delimiters_templates} ) {
196 if ( ! defined( $v->{$f}->{$template} ) ) {
197 $errors->{$f}->{potentially_invalid_combination} = $template;
198 $errors->{$f}->{dump} = $subfield_dump;
199 #} else {
200 # warn "## $f $template ok\n";
201 }
202 }
203 }
204 }
205 }
206
207 next unless ( $r ); # skip validation of no rules are specified
208
209 next if (defined( $self->{dont_validate}->{$f} ));
210
211 # track field usage
212 $fields->{$f}++;
213
214 if ( ! defined($r->{$f}) ) {
215 $errors->{ $f }->{unexpected} = "this field is not expected";
216 next;
217 }
218
219
220 if (ref($rec->{$f}) ne 'ARRAY') {
221 $errors->{ $f }->{not_repeatable} = "probably bug in parsing input data";
222 next;
223 }
224
225 foreach my $v (@{ $rec->{$f} }) {
226 # can we have subfields?
227 if (ref($r->{$f}) eq 'ARRAY') {
228 # are values hashes? (has subfields)
229 if (! defined($v)) {
230 # $errors->{$f}->{empty} = undef;
231 # $errors->{dump} = $rec_dump if ($rec_dump);
232 } elsif (ref($v) ne 'HASH') {
233 $errors->{$f}->{missing_subfield} = join(",", @{ $r->{$f} }) . " required";
234 next;
235 } else {
236
237 my $h = dclone( $v );
238
239 my $sf_repeatable;
240
241 delete($v->{subfields}) if (defined($v->{subfields}));
242
243 my $subfields;
244
245 foreach my $sf (keys %{ $v }) {
246
247 $subfields->{ $sf }++;
248
249 # is non-repeatable but with multiple values?
250 if ( ! first { $_ eq $sf.'*' } @{$r->{$f}} ) {
251 if ( ref($v->{$sf}) eq 'ARRAY' ) {
252 $sf_repeatable->{$sf}++;
253 };
254 if (! first { $_ eq $sf } @{ $r->{$f} }) {
255 $errors->{ $f }->{subfield}->{extra}->{$sf}++;
256 }
257 }
258
259 }
260 if (my @r_sf = sort keys( %$sf_repeatable )) {
261
262 foreach my $sf (@r_sf) {
263 $errors->{$f}->{subfield}->{extra_repeatable}->{$sf}++;
264 $errors->{$f}->{dump} = _pack_subfields_hash( $h, 1 );
265 }
266
267 }
268
269 if ( defined( $self->{must_exist_sf}->{$f} ) ) {
270 foreach my $sf (sort keys %{ $self->{must_exist_sf}->{$f} }) {
271 #warn "====> $f $sf must exist\n";
272 $errors->{$f}->{subfield}->{missing}->{$sf}++
273 unless defined( $subfields->{$sf} );
274 }
275 }
276
277 }
278 } elsif (ref($v) eq 'HASH') {
279 $errors->{$f}->{unexpected_subfields}++;
280 $errors->{$f}->{dump} = _pack_subfields_hash( $v, 1 );
281 }
282 }
283 }
284
285 $log->debug("_delimiters_templates = ", sub { dump( $self->{_delimiters_templates} ) } );
286
287 foreach my $must (sort keys %{ $self->{must_exist} }) {
288 next if ($fields->{$must});
289 $errors->{$must}->{missing}++;
290 $errors->{dump} = $rec_dump if ($rec_dump);
291 }
292
293 if ($errors) {
294 $log->debug("errors: ", $self->report_error( $errors ) );
295
296 my $mfn = $rec->{'000'}->[0] || $log->logconfess("record ", sub { dump( $rec ) }, " doesn't have MFN");
297 $self->{errors}->{$mfn} = $errors;
298 }
299
300 #$log->logcluck("return from this function is ARRAY") unless wantarray;
301
302 return $errors;
303 }
304
305 =head2 reset
306
307 Clean all accumulated errors for this input and remember delimiter templates
308 for L<save_delimiters_templates>
309
310 $validate->reset;
311
312 This function B<must> be called after each input to provide accurate statistics.
313
314 =cut
315
316 sub reset {
317 my $self = shift;
318
319 my $log = $self->_get_logger;
320
321 delete ($self->{errors});
322
323 if ( ! $self->{_delimiters_templates} ) {
324 $log->debug("called without _delimiters_templates?");
325 return;
326 }
327
328 foreach my $f ( keys %{ $self->{_delimiters_templates} } ) {
329 foreach my $t ( keys %{ $self->{_delimiters_templates}->{$f} } ) {
330 $self->{_accumulated_delimiters_templates}->{$f}->{$t} +=
331 $self->{_delimiters_templates}->{$f}->{$t};
332 }
333 }
334 $log->debug("_accumulated_delimiters_templates = ", sub { dump( $self->{_accumulated_delimiter_templates} ) } );
335 delete ($self->{_delimiters_templates});
336 }
337
338 =head2 all_errors
339
340 Return hash with all errors
341
342 print dump( $validate->all_errors );
343
344 =cut
345
346 sub all_errors {
347 my $self = shift;
348 return $self->{errors};
349 }
350
351 =head2 report_error
352
353 Produce nice humanly readable report of single error
354
355 print $validate->report_error( $error_hash );
356
357 =cut
358
359 sub report_error {
360 my $self = shift;
361
362 my $h = shift || die "no hash?";
363
364 sub _unroll {
365 my ($self, $tree, $accumulated) = @_;
366
367 my $log = $self->_get_logger();
368
369 $log->debug("# ",
370 ( $tree ? "tree: $tree " : '' ),
371 ( $accumulated ? "accumulated: $accumulated " : '' ),
372 );
373
374 my $results;
375
376 if (ref($tree) ne 'HASH') {
377 return ("$accumulated\t($tree)", undef);
378 }
379
380 my $dump;
381
382 foreach my $k (sort keys %{ $tree }) {
383
384 if ($k eq 'dump') {
385 $dump = $tree->{dump};
386 #warn "## dump ",dump($dump),"\n";
387 next;
388 }
389
390 $log->debug("current: $k");
391
392 my ($new_results, $new_dump) = $self->_unroll($tree->{$k},
393 $accumulated ? "$accumulated\t$k" : $k
394 );
395
396 $log->debug( "new_results: ", sub { dump($new_results) } ) if ( $new_results );
397
398 push @$results, $new_results if ($new_results);
399 $dump = $new_dump if ($new_dump);
400
401 }
402
403 $log->debug( "results: ", sub { dump($results) } ) if ( $results );
404
405 if ($#$results == 0) {
406 return ($results->[0], $dump);
407 } else {
408 return ($results, $dump);
409 }
410 }
411
412
413 sub _reformat {
414 my $l = shift;
415 $l =~ s/\t/ /g;
416 $l =~ s/_/ /g;
417 return $l;
418 }
419
420 my $out = '';
421
422 for my $f (sort keys %{ $h }) {
423 $out .= "$f: ";
424
425 my ($r, $d) = $self->_unroll( $h->{$f} );
426 my $e;
427 if (ref($r) eq 'ARRAY') {
428 $e .= join(", ", map { _reformat( $_ ) } @$r);
429 } else {
430 $e .= _reformat( $r );
431 }
432 $e .= "\n\t$d" if ($d);
433
434 $out .= $e . "\n";
435 }
436 return $out;
437 }
438
439
440 =head2 report
441
442 Produce nice humanly readable report of errors
443
444 print $validate->report;
445
446 =cut
447
448 sub report {
449 my $self = shift;
450 my $e = $self->{errors} || return;
451
452 my $out;
453 foreach my $mfn (sort { $a <=> $b } keys %$e) {
454 $out .= "MFN $mfn\n" . $self->report_error( $e->{$mfn} ) . "\n";
455 }
456
457 return $out;
458
459 }
460
461 =head2 delimiters_templates
462
463 Generate report of delimiter tamplates
464
465 my $report = $validate->delimiter_teplates(
466 report => 1,
467 current_input => 1,
468 );
469
470 Options:
471
472 =over 4
473
474 =item report
475
476 Generate humanly readable report with single fields
477
478 =item current_input
479
480 Report just current_input and not accumulated data
481
482 =back
483
484 =cut
485
486 sub delimiters_templates {
487 my $self = shift;
488
489 my $args = {@_};
490
491 my $t = $self->{_accumulated_delimiters_templates};
492 $t = $self->{_delimiters_templates} if ( $args->{current_input} );
493
494 my $log = $self->_get_logger;
495
496 unless ($t) {
497 $log->error("called without delimiters");
498 return;
499 }
500
501 my $out;
502
503 foreach my $f (sort { $a <=> $b } keys %$t) {
504 $out .= "$f\n" if ( $args->{report} );
505 foreach my $template (sort { $a cmp $b } keys %{ $t->{$f} }) {
506 my $count = $t->{$f}->{$template};
507 $out .=
508 ( $count ? "" : "# " ) .
509 ( $args->{report} ? "" : "$f" ) .
510 "\t$count\t$template\n";
511 }
512 }
513
514 return $out;
515 }
516
517 =head2 save_delimiters_templates
518
519 Save accumulated delimiter templates
520
521 $validator->save_delimiters_template( '/path/to/validate/delimiters' );
522
523 =cut
524
525 sub save_delimiters_templates {
526 my $self = shift;
527
528 my $path = $self->{delimiters_path};
529
530 return unless ( $path );
531
532 my $log = $self->_get_logger;
533
534 if ( ! $self->{_accumulated_delimiters_templates} ) {
535 $log->error('no _accumulated_delimiters_templates found, reset');
536 $self->reset;
537 }
538
539 if ( ! $self->{_delimiters_templates} ) {
540 $log->error('found _delimiters_templates, calling reset');
541 $self->reset;
542 }
543
544 $path .= '.new' if ( -e $path );
545
546 open(my $d, '>', $path) || $log->fatal("can't open $path: $!");
547 print $d $self->delimiters_templates;
548 close($d);
549
550 $log->info("new delimiters templates saved to $path");
551 }
552
553 =head1 AUTHOR
554
555 Dobrica Pavlinusic, C<< <dpavlin@rot13.org> >>
556
557 =head1 COPYRIGHT & LICENSE
558
559 Copyright 2006 Dobrica Pavlinusic, All Rights Reserved.
560
561 This program is free software; you can redistribute it and/or modify it
562 under the same terms as Perl itself.
563
564 =cut
565
566 1; # End of WebPAC::Validate

  ViewVC Help
Powered by ViewVC 1.1.26